Skip to content

Commit a552a41

Browse files
authored
Create 2192. All Ancestors of a Node in a Directed Acyclic Graph (#516)
2 parents 19ae111 + 04268a5 commit a552a41

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
4+
vector<vector<int>> ans(n), directChild(n);
5+
for (auto& e : edges) {
6+
directChild[e[0]].push_back(e[1]);
7+
}
8+
for (int i = 0; i < n; i++) {
9+
dfs(i, i, ans, directChild);
10+
}
11+
return ans;
12+
}
13+
14+
private:
15+
void dfs(int x, int curr, vector<vector<int>>& ans, vector<vector<int>>& directChild) {
16+
for (int ch : directChild[curr]) {
17+
if (ans[ch].empty() || ans[ch].back() != x) {
18+
ans[ch].push_back(x);
19+
dfs(x, ch, ans, directChild);
20+
}
21+
}
22+
}
23+
};

0 commit comments

Comments
 (0)