-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetAnt.cpp
More file actions
33 lines (28 loc) · 914 Bytes
/
getAnt.cpp
File metadata and controls
33 lines (28 loc) · 914 Bytes
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
class Solution {
public:
vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
vector<vector<int>> res(n);
vector<vector<int>> graph(n);
for (const auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
}
for (int i = 0; i < n; ++i) {
vector<bool> visit(n, false);
dfs(graph, i, i, res, visit);
}
for (int i = 0; i < n; ++i) {
sort(res[i].begin(), res[i].end());
}
return res;
}
private:
void dfs(vector<vector<int>>& graph, int parent, int curr, vector<vector<int>>& res, vector<bool>& visit) {
visit[curr] = true;
for (int dest : graph[curr]) {
if (!visit[dest]) {
res[dest].push_back(parent);
dfs(graph, parent, dest, res, visit);
}
}
}
};