Skip to content

Commit 63726a9

Browse files
author
Mayank Kumar Jha
authored
Create dfs.java
1 parent d6b6012 commit 63726a9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

dfs.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.*;
2+
3+
public class App{
4+
5+
6+
public static void dfs(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
7+
byte []b=new byte[vertices]; //flag container containing status of each vertices
8+
Arrays.fill(b,(byte)-1); //status initialization
9+
/* code status
10+
-1 = ready
11+
0 = waiting
12+
1 = processed */
13+
14+
15+
Stack <Integer> st=new Stack<>(); //operational stack
16+
st.push(source); //assigning source
17+
while(!st.isEmpty()){
18+
b[st.peek()]=(byte)0; //assigning waiting status
19+
System.out.println(st.peek());
20+
int pop=st.pop();
21+
b[pop]=(byte)1; //assigning processed status
22+
for(int i=0;i<vertices;i++){
23+
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
24+
st.push(i);
25+
b[i]=(byte)0; //assigning waiting status
26+
}}}
27+
28+
}
29+
30+
public static void main(String args[]){
31+
Scanner in=new Scanner(System.in);
32+
int vertices=in.nextInt(),source=in.nextInt();
33+
byte [][]a=new byte [vertices][vertices];
34+
//initially all elements of a are initialized with value zero
35+
36+
for(int i=0;i<vertices;i++){
37+
int size =in.nextInt();
38+
for(int j=0;j<size;j++){
39+
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
40+
}
41+
}
42+
bfs(a,vertices,source); //function call
43+
}}

0 commit comments

Comments
 (0)