-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphBFS.java
67 lines (54 loc) · 1.63 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
import java.io.*;
/*
* BFS (neerest first)
* LinkedList[] adj 와 queue 로 구현
* vertice num 이 adj 의 index로 작용, value 는 adjecent node num
* boolean[] visited 역시 index로 vertice num 사용
* cycle 대응 가능
*
* */
public class GraphBFS {
private int numberOfVertices;
private LinkedList<Integer> adj[];
GraphBFS(int v) {
numberOfVertices = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList();
}
}
void addNode(int v, int adjVertice) {
adj[v].add(adjVertice);
}
void traverse(int startingVertice) {
LinkedList<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[numberOfVertices];
queue.add(startingVertice);
visited[startingVertice] = true;
while (queue.size() != 0) {
int cur = queue.poll();
System.out.print(cur + " -> ");
Iterator iter = adj[cur].iterator();
while (iter.hasNext()) {
int adjVertice = (int) iter.next();
if (!visited[adjVertice]) {
visited[adjVertice] = true;
queue.add(adjVertice);
}
}
}
}
public static void main(String[] args) {
GraphBFS graph = new GraphBFS(6);
graph.addNode(0, 1);
graph.addNode(0, 2);
graph.addNode(1, 2);
graph.addNode(2, 0);
graph.addNode(2, 3);
graph.addNode(3, 3);
graph.addNode(3, 4);
graph.addNode(3, 5);
graph.traverse(2);
}
}