-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstSearch.java
More file actions
54 lines (45 loc) · 1.16 KB
/
DepthFirstSearch.java
File metadata and controls
54 lines (45 loc) · 1.16 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
package Graph;
import java.util.*;
public class DepthFirstSearch {
private boolean[] visited;
private int count;
private int[] edgeTo;
private int start;
public DepthFirstSearch(Graph g, int start) {
visited = new boolean[g.V()];
edgeTo = new int[g.V()];
this.start = start;
dfs(g, start);
}
public void dfs(Graph g, int s) {
visited[s] = true;
count++;
for (int w : g.adj(s)) {
if (!visited[w]) {
edgeTo[w] = s;
dfs(g, w);
}
}
}
public boolean visited(int v) {
return visited[v];
}
public int count() {
return count;
}
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;
}
}