-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathsolution.cpp
More file actions
52 lines (44 loc) · 1.39 KB
/
Copy pathsolution.cpp
File metadata and controls
52 lines (44 loc) · 1.39 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
class Solution {
public:
vector<int> remainingMethods(int n, int k, vector<vector<int>>& invocations) {
// Build the directed graph
vector<vector<int>> graph(n);
for (auto &edge : invocations) {
graph[edge[0]].push_back(edge[1]);
}
// Marks whether a method is suspicious
vector<bool> vis(n, false);
// DFS to mark every method reachable from k
function<void(int)> dfs = [&](int u) {
vis[u] = true;
// Visit every invoked method
for (int v : graph[u]) {
if (!vis[v]) {
dfs(v);
}
}
};
dfs(k);
// Check whether any non-suspicious method calls a suspicious one
for (auto &edge : invocations) {
int u = edge[0];
int v = edge[1];
if (!vis[u] && vis[v]) {
// Removal is impossible, return all methods
vector<int> ans;
for (int i = 0; i < n; i++) {
ans.push_back(i);
}
return ans;
}
}
// Keep only non-suspicious methods
vector<int> ans;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
ans.push_back(i);
}
}
return ans;
}
};