-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearch.java
More file actions
49 lines (41 loc) · 1.27 KB
/
BreadthFirstSearch.java
File metadata and controls
49 lines (41 loc) · 1.27 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
41
42
43
44
45
46
47
48
49
package Graph;
import java.util.*;
public class BreadthFirstSearch {
private boolean[] visited;
private int[] edgeTo;
private int start;
public BreadthFirstSearch(Graph g, int start) {
this.start = start;
visited = new boolean[g.V()];
edgeTo = new int[g.V()];
bfs(g, start);
}
public void bfs(Graph g, int start) {
Queue<Integer> queue = new LinkedList<Integer>();
visited[start] = true;
queue.offer(start);
while (!queue.isEmpty()) {
int front = queue.poll();
for (int neighbor : g.adj(front)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
edgeTo[neighbor] = front;
queue.offer(neighbor);
}
}
}
}
public boolean hasPathTo(int v) {return visited[v];}
public Iterable<Integer> pathTo(int v) {
List<Integer> path = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
for (int x = v; x != start; x = edgeTo[x]) {
stack.push(x);
}
stack.push(start);
while(!stack.isEmpty()) {
path.add(stack.pop());
}
return path;
}
}