-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathGraphBFS.java
48 lines (37 loc) · 1.05 KB
/
GraphBFS.java
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
41
42
43
44
45
46
47
48
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class GraphBFS {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> order = new ArrayList<>();
public GraphBFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
bfs(v);
}
private void bfs(int s){
Queue<Integer> queue = new LinkedList<>();
queue.add(s);
visited[s] = true;
while(!queue.isEmpty()){
int v = queue.remove();
order.add(v);
for(int w: G.adj(v))
if(!visited[w]){
queue.add(w);
visited[w] = true;
}
}
}
public Iterable<Integer> order(){
return order;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
GraphBFS graphBFS = new GraphBFS(g);
System.out.println("BFS Order : " + graphBFS.order());
}
}