-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSampleBFSWithQueue.java
More file actions
40 lines (32 loc) · 1.17 KB
/
Copy pathSampleBFSWithQueue.java
File metadata and controls
40 lines (32 loc) · 1.17 KB
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.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class SampleBFSWithQueue {
public static void main(String[] args) {
int[][] graph = { { 0, 1, 0, 0, 0, 0, 0},
{ 1, 0, 1, 0, 0, 0, 1},
{ 0, 1, 0, 1, 1, 1, 1},
{ 0, 0, 1, 0, 0, 1, 0},
{ 0, 0, 1, 0, 0, 1, 0},
{ 0, 0, 1, 1, 1, 0, 0},
{ 0, 1, 1, 0, 0, 0, 0}};
//Khai báo
Queue<Integer> queue = new LinkedList<>();
Set<Integer> daDuyet = new HashSet<>();
//Chọn đỉnh đầu là 0
queue.add(0);
daDuyet.add(0);
while(!queue.isEmpty()){
int u = queue.poll();
System.out.print(u + "\t");
//Add tất cả đỉnh kề v với u mà chưa được duyệt vào queue
for (int v = 0; v < graph.length; v++) {
if(graph[u][v] == 1 && daDuyet.contains(v) == false){
queue.add(v);
daDuyet.add(v);
}
}
}
}
}