-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsolution.java
More file actions
56 lines (46 loc) · 1.44 KB
/
Copy pathsolution.java
File metadata and controls
56 lines (46 loc) · 1.44 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
class Solution {
public List<Integer> remainingMethods(int n, int k, int[][] invocations) {
// Build the adjacency list
List<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int[] edge : invocations) {
graph[edge[0]].add(edge[1]);
}
// Marks suspicious methods
boolean[] vis = new boolean[n];
// DFS from method k
dfs(k, graph, vis);
// If a safe method invokes a suspicious one,
// removal is not allowed
for (int[] edge : invocations) {
int u = edge[0];
int v = edge[1];
if (!vis[u] && vis[v]) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
ans.add(i);
}
return ans;
}
}
// Return remaining methods
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!vis[i]) {
ans.add(i);
}
}
return ans;
}
// DFS to mark all reachable methods
private void dfs(int u, List<Integer>[] graph, boolean[] vis) {
vis[u] = true;
for (int v : graph[u]) {
if (!vis[v]) {
dfs(v, graph, vis);
}
}
}
}