Merge pull request #13 from mk9440/master

dfs.java
This commit is contained in:
Chetan Kaushik 2017-04-07 22:09:13 +05:30 committed by GitHub
commit 2ae6cc2835
2 changed files with 85 additions and 0 deletions

42
bfs.java Normal file
View File

@ -0,0 +1,42 @@
import java.util.*;
public class App{
public static void bfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Queue <Integer> st=new LinkedList<>(); //operational stack
st.add(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.element());
int pop=st.element();
b[pop]=(byte)1; //assigning processed status
st.remove(); //removing head of the queue
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.add(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
bfs(a,vertices,source); //function call
}}

43
dfs.java Normal file
View File

@ -0,0 +1,43 @@
import java.util.*;
public class App{
public static void dfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
/* code status
-1 = ready
0 = waiting
1 = processed */
Stack <Integer> st=new Stack<>(); //operational stack
st.push(source); //assigning source
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.pop();
b[pop]=(byte)1; //assigning processed status
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
b[i]=(byte)0; //assigning waiting status
}}}
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
for(int i=0;i<vertices;i++){
int size =in.nextInt();
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
bfs(a,vertices,source); //function call
}}