forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
32 lines (32 loc) · 857 Bytes
/
Solution.cpp
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
class Solution {
public:
vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
vector<int> g[n];
for (auto& e : edges) {
g[e[0]].push_back(e[1]);
}
vector<vector<int>> ans(n);
auto bfs = [&](int s) {
queue<int> q;
q.push(s);
bool vis[n];
memset(vis, 0, sizeof(vis));
vis[s] = true;
while (q.size()) {
int i = q.front();
q.pop();
for (int j : g[i]) {
if (!vis[j]) {
vis[j] = true;
ans[j].push_back(s);
q.push(j);
}
}
}
};
for (int i = 0; i < n; ++i) {
bfs(i);
}
return ans;
}
};