-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_1059.java
More file actions
34 lines (29 loc) · 1 KB
/
Copy pathP_1059.java
File metadata and controls
34 lines (29 loc) · 1 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
package leetcode.medium;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class P_1059 {
enum State {
PROCESSING, PROCESSED
}
public boolean leadsToDestination(int n, int[][] edges, int src, int dest) {
final Map<Integer, List<Integer>> g = new HashMap<>();
for (int[] e : edges) {
g.computeIfAbsent(e[0], v -> new ArrayList<>()).add(e[1]);
}
return leadsToDest(g, src, dest, new State[n]);
}
private static boolean leadsToDest(Map<Integer, List<Integer>> g, int node, int dest, State[] states) {
if (states[node] != null) { return states[node] == State.PROCESSED; }
if (!g.containsKey(node)) { return node == dest; }
states[node] = State.PROCESSING;
for (int next : g.get(node)) {
if (!leadsToDest(g, next, dest, states)) {
return false;
}
}
states[node] = State.PROCESSED;
return true;
}
}