-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
39 lines (36 loc) · 744 Bytes
/
DFS.java
File metadata and controls
39 lines (36 loc) · 744 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.*;
class DFS{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int v = scan.nextInt();
int mat[][] = new int[v][v];
for(int i=0;i<v;i++){
for(int j=0;j<v;j++){
mat[i][j] = scan.nextInt();
}
}
dfs(mat,v);
}
static void dfs(int mat[][], int v){
boolean visited[] = new boolean[v];
Stack<Integer> stack = new Stack<Integer>();
visited[0] = true;
stack.add(0);
int node = stack.pop();
System.out.print(node+" ");
while(true){
for(int i=0;i<v;i++){
if(mat[node][i]==1 && visited[i]){
stack.push(i);
visited[i] = true;
}
}
if(stack.size()==0){
break;
}else{
node = stack.pop();
System.out.print(node+" ");
}
}
}
}