67
67
68
68
** 方法一:BFS**
69
69
70
+ 我们先根据二维数组 $edges$ 构建邻接表 $g$,其中 $g[ i] $ 表示节点 $i$ 的所有后继节点。
71
+
72
+ 然后我们从小到大枚举节点 $i$ 作为祖先节点,使用 BFS 搜索节点 $i$ 的所有后继节点,把节点 $i$ 加入这些后继节点的祖先列表中。
73
+
74
+ 时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$。其中 $n$ 是节点数。
75
+
70
76
<!-- tabs:start -->
71
77
72
78
### ** Python3**
76
82
``` python
77
83
class Solution :
78
84
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
+
79
96
g = defaultdict(list )
80
97
for u, v in edges:
81
- g[v ].append(u )
82
- ans = []
98
+ g[u ].append(v )
99
+ ans = [[] for _ in range (n) ]
83
100
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)
100
102
return ans
101
103
```
102
104
@@ -106,39 +108,42 @@ class Solution:
106
108
107
109
``` java
108
110
class Solution {
111
+ private int n;
112
+ private List<Integer > [] g;
113
+ private List<List<Integer > > ans;
114
+
109
115
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 ]);
114
121
}
115
- List< List< Integer > > ans = new ArrayList<> ();
122
+ ans = new ArrayList<> ();
116
123
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);
136
144
}
137
145
}
138
- Collections . sort(t);
139
- ans. add(t);
140
146
}
141
- return ans;
142
147
}
143
148
}
144
149
```
@@ -149,32 +154,31 @@ class Solution {
149
154
class Solution {
150
155
public:
151
156
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);
173
176
}
174
177
}
175
178
}
176
- sort(t.begin(), t.end());
177
- ans.push_back(t);
179
+ };
180
+ for (int i = 0; i < n; ++i) {
181
+ bfs(i);
178
182
}
179
183
return ans;
180
184
}
@@ -187,33 +191,27 @@ public:
187
191
func getAncestors(n int, edges [][]int) [][]int {
188
192
g := make([][]int, n)
189
193
for _, e := range edges {
190
- g[e[1 ]] = append(g[e[1 ]], e[0 ])
194
+ g[e[0 ]] = append(g[e[0 ]], e[1 ])
191
195
}
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}
200
199
vis := make([]bool, n)
201
- vis[i ] = true
200
+ vis[s ] = true
202
201
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)
212
209
}
213
210
}
214
211
}
215
- sort.Ints(t)
216
- ans = append(ans, t)
212
+ }
213
+ for i := 0; i < n; i++ {
214
+ bfs(i)
217
215
}
218
216
return ans
219
217
}
@@ -222,7 +220,32 @@ func getAncestors(n int, edges [][]int) [][]int {
222
220
### ** TypeScript**
223
221
224
222
``` 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
+ }
226
249
```
227
250
228
251
### ** ...**
0 commit comments