-
Notifications
You must be signed in to change notification settings - Fork 0
/
BreadthFirstPaths.java
73 lines (65 loc) · 1.31 KB
/
BreadthFirstPaths.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
68
69
70
71
72
73
package fundamentals.graph;
import java.util.ArrayDeque;
import java.util.Stack;
/**
* The type Breadth first paths.
*/
public class BreadthFirstPaths {
private boolean[] marked;
private int[] edgeTo;
private final int s;
/**
* Instantiates a new Breadth first paths.
*
* @param G the g
* @param s the s
*/
public BreadthFirstPaths(Graph G, int s) {
marked = new boolean[G.V()];
edgeTo = new int[G.V()];
this.s = s;
bfs(G, s);
}
private void bfs(Graph G, int s) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
marked[s] = true;
queue.offer(s);
queue.add(s);
while (!queue.isEmpty()) {
int v = queue.poll();
for (int w : G.adj(v)) {
if (!marked[w]) {
edgeTo[w] = v;
marked[w] = true;
queue.offer(w);
}
}
}
}
/**
* Has path to boolean.
*
* @param v the v
* @return the boolean
*/
public boolean hasPathTo(int v) {
return marked[v];
}
/**
* Path to iterable.
*
* @param v the v
* @return the iterable
*/
public Iterable<Integer> pathTo(int v) {
if (!hasPathTo(v)) {
return null;
}
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x]) {
path.push(x);
}
path.push(s);
return path;
}
}