-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
40 lines (36 loc) · 750 Bytes
/
BFS.java
File metadata and controls
40 lines (36 loc) · 750 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
40
import java.util.*;
class BFS{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int mat[][] = new int[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
mat[i][j] = scan.nextInt();
}
}
dfs(mat,n);
}
static void dfs(int mat[][],int n){
int visited[] = new int[n];
LinkedList <Integer> queue = new LinkedList<>();
visited[0]=1;
queue.add(0);
int node = (int)queue.poll();
System.out.print(node+" ");
while(true){
for(int i=0;i<n;i++){
if(mat[node][i]==1 && visited[i]==0){
queue.add(i);
visited[i] = 1;
}
}
if(queue.size()==0){
break;
}else{
node = (int)queue.poll();
System.out.print(node+" ");
}
}
}
}