-
Notifications
You must be signed in to change notification settings - Fork 13
/
DepthFirstPaths.java
65 lines (52 loc) · 1.17 KB
/
DepthFirstPaths.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
package leetcode.graph.algorithms;
import leetcode.graph.algorithms.basic.Graph;
import java.util.Stack;
/**
* 深度优先搜索算法
*
* @author FangYuan
* @since 2024-01-24 21:25:58
*/
public class DepthFirstPaths {
/**
* 标记是否能经过
*/
private boolean[] marked;
/**
* 记录父节点
*/
private int[] edgeTo;
/**
* 起点
*/
private final int s;
public DepthFirstPaths(Graph graph, int s) {
this.s = s;
edgeTo = new int[graph.V()];
marked = new boolean[graph.V()];
dfs(graph, s);
}
private void dfs(Graph graph, int s) {
marked[s] = true;
for (Integer v : graph.adj(s)) {
if (!marked[v]) {
edgeTo[v] = s;
dfs(graph, v);
}
}
}
public boolean hasPathTo(int s) {
return marked[s];
}
public Stack<Integer> pathTo(int v) {
if (!hasPathTo(v)) {
return null;
}
Stack<Integer> stack = new Stack<>();
for (int w = v; w != s; w = edgeTo[w]) {
stack.push(w);
}
stack.push(s);
return stack;
}
}