-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedBFS.java
More file actions
57 lines (50 loc) · 1.4 KB
/
DirectedBFS.java
File metadata and controls
57 lines (50 loc) · 1.4 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
50
51
52
53
54
55
56
57
package Graph;
import java.util.*;
public class DirectedBFS {
private boolean[] visited;
private int[] pathTo;
private int[] distTo;
// private int start;
public DirectedBFS(DirectedGraph g, int s) {
// start = s;
visited = new boolean[g.V()];
pathTo = new int[g.V()];
distTo = new int[g.V()];
pathTo[s] = s;
bfs(g, s);
}
public void bfs(DirectedGraph g, int s) {
Queue<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
distTo[s] = 0;
queue.offer(s);
while(!queue.isEmpty()) {
int v = queue.poll();
for (int w : g.adj(v)) {
if (!visited[w]){
visited[w] = true;
distTo[w] = distTo[v] + 1;
pathTo[w] = v;
queue.offer(w);
}
}
}
}
public boolean hasPathTo(int v) {
return visited[v];
}
public Iterable<Integer> pathTo(int v) {
if (!hasPathTo(v)) return null;
List<Integer> list = new ArrayList<Integer>();
Stack<Integer> stack = new Stack<Integer>();
int x = v;
for (; distTo[x] != 0; x = pathTo[x]) {
stack.push(x);
}
stack.push(x);
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
}