Skip to content

Commit 66da16b

Browse files
authored
feat: add solutions to lc problem: No.2192 (#1631)
No.2192.All Ancestors of a Node in a Directed Acyclic Graph
1 parent e583f06 commit 66da16b

File tree

7 files changed

+327
-269
lines changed

7 files changed

+327
-269
lines changed

solution/2100-2199/2192.All Ancestors of a Node in a Directed Acyclic Graph/README.md

+113-90
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@
6767

6868
**方法一:BFS**
6969

70+
我们先根据二维数组 $edges$ 构建邻接表 $g$,其中 $g[i]$ 表示节点 $i$ 的所有后继节点。
71+
72+
然后我们从小到大枚举节点 $i$ 作为祖先节点,使用 BFS 搜索节点 $i$ 的所有后继节点,把节点 $i$ 加入这些后继节点的祖先列表中。
73+
74+
时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是节点数。
75+
7076
<!-- tabs:start -->
7177

7278
### **Python3**
@@ -76,27 +82,23 @@
7682
```python
7783
class Solution:
7884
def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
85+
def bfs(s: int):
86+
q = deque([s])
87+
vis = {s}
88+
while q:
89+
i = q.popleft()
90+
for j in g[i]:
91+
if j not in vis:
92+
vis.add(j)
93+
q.append(j)
94+
ans[j].append(s)
95+
7996
g = defaultdict(list)
8097
for u, v in edges:
81-
g[v].append(u)
82-
ans = []
98+
g[u].append(v)
99+
ans = [[] for _ in range(n)]
83100
for i in range(n):
84-
if not g[i]:
85-
ans.append([])
86-
continue
87-
q = deque([i])
88-
vis = [False] * n
89-
vis[i] = True
90-
t = []
91-
while q:
92-
for _ in range(len(q)):
93-
v = q.popleft()
94-
for u in g[v]:
95-
if not vis[u]:
96-
vis[u] = True
97-
q.append(u)
98-
t.append(u)
99-
ans.append(sorted(t))
101+
bfs(i)
100102
return ans
101103
```
102104

@@ -106,39 +108,42 @@ class Solution:
106108

107109
```java
108110
class Solution {
111+
private int n;
112+
private List<Integer>[] g;
113+
private List<List<Integer>> ans;
114+
109115
public List<List<Integer>> getAncestors(int n, int[][] edges) {
110-
List<Integer>[] g = new List[n];
111-
Arrays.setAll(g, k -> new ArrayList<>());
112-
for (int[] e : edges) {
113-
g[e[1]].add(e[0]);
116+
g = new List[n];
117+
this.n = n;
118+
Arrays.setAll(g, i -> new ArrayList<>());
119+
for (var e : edges) {
120+
g[e[0]].add(e[1]);
114121
}
115-
List<List<Integer>> ans = new ArrayList<>();
122+
ans = new ArrayList<>();
116123
for (int i = 0; i < n; ++i) {
117-
List<Integer> t = new ArrayList<>();
118-
if (g[i].isEmpty()) {
119-
ans.add(t);
120-
continue;
121-
}
122-
Deque<Integer> q = new ArrayDeque<>();
123-
q.offer(i);
124-
boolean[] vis = new boolean[n];
125-
vis[i] = true;
126-
while (!q.isEmpty()) {
127-
for (int j = q.size(); j > 0; --j) {
128-
int v = q.poll();
129-
for (int u : g[v]) {
130-
if (!vis[u]) {
131-
vis[u] = true;
132-
q.offer(u);
133-
t.add(u);
134-
}
135-
}
124+
ans.add(new ArrayList<>());
125+
}
126+
for (int i = 0; i < n; ++i) {
127+
bfs(i);
128+
}
129+
return ans;
130+
}
131+
132+
private void bfs(int s) {
133+
Deque<Integer> q = new ArrayDeque<>();
134+
q.offer(s);
135+
boolean[] vis = new boolean[n];
136+
vis[s] = true;
137+
while (!q.isEmpty()) {
138+
int i = q.poll();
139+
for (int j : g[i]) {
140+
if (!vis[j]) {
141+
vis[j] = true;
142+
q.offer(j);
143+
ans.get(j).add(s);
136144
}
137145
}
138-
Collections.sort(t);
139-
ans.add(t);
140146
}
141-
return ans;
142147
}
143148
}
144149
```
@@ -149,32 +154,31 @@ class Solution {
149154
class Solution {
150155
public:
151156
vector<vector<int>> getAncestors(int n, vector<vector<int>>& edges) {
152-
vector<vector<int>> g(n);
153-
for (auto& e : edges) g[e[1]].push_back(e[0]);
154-
vector<vector<int>> ans;
155-
for (int i = 0; i < n; ++i) {
156-
vector<int> t;
157-
if (g[i].empty()) {
158-
ans.push_back(t);
159-
continue;
160-
}
161-
queue<int> q{{i}};
162-
vector<bool> vis(n);
163-
vis[i] = true;
164-
while (!q.empty()) {
165-
for (int j = q.size(); j > 0; --j) {
166-
int v = q.front();
167-
q.pop();
168-
for (int u : g[v]) {
169-
if (vis[u]) continue;
170-
vis[u] = true;
171-
q.push(u);
172-
t.push_back(u);
157+
vector<int> g[n];
158+
for (auto& e : edges) {
159+
g[e[0]].push_back(e[1]);
160+
}
161+
vector<vector<int>> ans(n);
162+
auto bfs = [&](int s) {
163+
queue<int> q;
164+
q.push(s);
165+
bool vis[n];
166+
memset(vis, 0, sizeof(vis));
167+
vis[s] = true;
168+
while (q.size()) {
169+
int i = q.front();
170+
q.pop();
171+
for (int j : g[i]) {
172+
if (!vis[j]) {
173+
vis[j] = true;
174+
ans[j].push_back(s);
175+
q.push(j);
173176
}
174177
}
175178
}
176-
sort(t.begin(), t.end());
177-
ans.push_back(t);
179+
};
180+
for (int i = 0; i < n; ++i) {
181+
bfs(i);
178182
}
179183
return ans;
180184
}
@@ -187,33 +191,27 @@ public:
187191
func getAncestors(n int, edges [][]int) [][]int {
188192
g := make([][]int, n)
189193
for _, e := range edges {
190-
g[e[1]] = append(g[e[1]], e[0])
194+
g[e[0]] = append(g[e[0]], e[1])
191195
}
192-
var ans [][]int
193-
for i := 0; i < n; i++ {
194-
var t []int
195-
if len(g[i]) == 0 {
196-
ans = append(ans, t)
197-
continue
198-
}
199-
q := []int{i}
196+
ans := make([][]int, n)
197+
bfs := func(s int) {
198+
q := []int{s}
200199
vis := make([]bool, n)
201-
vis[i] = true
200+
vis[s] = true
202201
for len(q) > 0 {
203-
for j := len(q); j > 0; j-- {
204-
v := q[0]
205-
q = q[1:]
206-
for _, u := range g[v] {
207-
if !vis[u] {
208-
vis[u] = true
209-
q = append(q, u)
210-
t = append(t, u)
211-
}
202+
i := q[0]
203+
q = q[1:]
204+
for _, j := range g[i] {
205+
if !vis[j] {
206+
vis[j] = true
207+
q = append(q, j)
208+
ans[j] = append(ans[j], s)
212209
}
213210
}
214211
}
215-
sort.Ints(t)
216-
ans = append(ans, t)
212+
}
213+
for i := 0; i < n; i++ {
214+
bfs(i)
217215
}
218216
return ans
219217
}
@@ -222,7 +220,32 @@ func getAncestors(n int, edges [][]int) [][]int {
222220
### **TypeScript**
223221

224222
```ts
225-
223+
function getAncestors(n: number, edges: number[][]): number[][] {
224+
const g: number[][] = Array.from({ length: n }, () => []);
225+
for (const [u, v] of edges) {
226+
g[u].push(v);
227+
}
228+
const ans: number[][] = Array.from({ length: n }, () => []);
229+
const bfs = (s: number) => {
230+
const q: number[] = [s];
231+
const vis: boolean[] = Array.from({ length: n }, () => false);
232+
vis[s] = true;
233+
while (q.length) {
234+
const i = q.shift()!;
235+
for (const j of g[i]) {
236+
if (!vis[j]) {
237+
vis[j] = true;
238+
ans[j].push(s);
239+
q.push(j);
240+
}
241+
}
242+
}
243+
};
244+
for (let i = 0; i < n; ++i) {
245+
bfs(i);
246+
}
247+
return ans;
248+
}
226249
```
227250

228251
### **...**

0 commit comments

Comments
 (0)