-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedDFS.java
More file actions
46 lines (39 loc) · 1.04 KB
/
DirectedDFS.java
File metadata and controls
46 lines (39 loc) · 1.04 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
package Graph;
import java.util.*;
public class DirectedDFS {
private boolean[] visited;
private int[] pathTo;
private int start;
public DirectedDFS(DirectedGraph g, int s) {
start = s;
visited = new boolean[g.V()];
pathTo = new int[g.V()];
dfs(g, s);
pathTo[s] = s;
}
public void dfs(DirectedGraph g, int v) {
visited[v] = true;
for (int w : g.adj(v)) {
if (!visited[w]) {
pathTo[w] = v;
dfs(g, 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>();
for (int x = v; x != start; x = pathTo[x]) {
stack.push(x);
}
stack.push(start);
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
}
}