-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
BFS.java
59 lines (43 loc) · 1.31 KB
/
BFS.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
package algo.graph;
import ds.graph.Graph;
import java.util.*;
/**
* Created by sherxon on 1/1/17.
*/
/**
* This is traditional top-down approach to traverse graph. This is advantageous when the frontier is small
*/
public class BFS {
protected Graph graph;
List<Integer> path = new LinkedList<>();
Queue<Integer> queue = new LinkedList<>();
public BFS(Graph graph) {
this.graph = graph;
}
public void search(Integer root) {
if (root == null || !graph.getVertices().contains(root)) return;
Set<Integer> visited = new HashSet<>();
visited.add(root);
queue.add(root);
processVertex(root);
while (!queue.isEmpty()) {
Integer vertex = queue.peek();
for (Integer neighbor : graph.getNeighbors(vertex))
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
processVertex(vertex);
}
queue.remove();
}
}
public void processVertex(Integer vertex) {
path.add(vertex);
}
public List<Integer> getPathFrom(Integer source) {
if (source == null || !graph.getVertices().contains(source))
return null;
search(source);
return path;
}
}