|
71 | 71 |
|
72 | 72 | **方法一:拓扑排序**
|
73 | 73 |
|
74 |
| -利用拓扑排序,找到一个合法的 $row$ 序列和 $col$ 序列,然后根据这两个序列构造出矩阵。 |
| 74 | +利用拓扑排序,找到一个合法的 `row` 序列和 `col` 序列,然后根据这两个序列构造出矩阵。 |
75 | 75 |
|
76 |
| -时间复杂度 $O(m+n+k^2)$。其中 $m$ 为 $rowConditions$ 的长度,$n$ 为 $colConditions$ 的长度,$k$ 为题目中的 $k$。 |
| 76 | +时间复杂度 $O(m+n+k)$。其中 $m$ 和 $n$ 分别为 `rowConditions` 和 `colConditions` 的长度,而 $k$ 为题目中给定的正整数。 |
77 | 77 |
|
78 | 78 | <!-- tabs:start -->
|
79 | 79 |
|
@@ -186,7 +186,7 @@ public:
|
186 | 186 | this->k = k;
|
187 | 187 | auto row = f(rowConditions);
|
188 | 188 | auto col = f(colConditions);
|
189 |
| - if (row.empty() || col.empty()) return vector<vector<int>>(); |
| 189 | + if (row.empty() || col.empty()) return {}; |
190 | 190 | vector<vector<int>> ans(k, vector<int>(k));
|
191 | 191 | vector<int> m(k + 1);
|
192 | 192 | for (int i = 0; i < k; ++i) {
|
@@ -291,7 +291,52 @@ func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int {
|
291 | 291 | ### **TypeScript**
|
292 | 292 |
|
293 | 293 | ```ts
|
| 294 | +function buildMatrix( |
| 295 | + k: number, |
| 296 | + rowConditions: number[][], |
| 297 | + colConditions: number[][], |
| 298 | +): number[][] { |
| 299 | + function f(cond) { |
| 300 | + const g = Array.from({ length: k + 1 }, () => []); |
| 301 | + const indeg = new Array(k + 1).fill(0); |
| 302 | + for (const [a, b] of cond) { |
| 303 | + g[a].push(b); |
| 304 | + ++indeg[b]; |
| 305 | + } |
| 306 | + const q = []; |
| 307 | + for (let i = 1; i < indeg.length; ++i) { |
| 308 | + if (indeg[i] == 0) { |
| 309 | + q.push(i); |
| 310 | + } |
| 311 | + } |
| 312 | + const res = []; |
| 313 | + while (q.length) { |
| 314 | + for (let n = q.length; n; --n) { |
| 315 | + const i = q.shift(); |
| 316 | + res.push(i); |
| 317 | + for (const j of g[i]) { |
| 318 | + if (--indeg[j] == 0) { |
| 319 | + q.push(j); |
| 320 | + } |
| 321 | + } |
| 322 | + } |
| 323 | + } |
| 324 | + return res.length == k ? res : []; |
| 325 | + } |
294 | 326 |
|
| 327 | + const row = f(rowConditions); |
| 328 | + const col = f(colConditions); |
| 329 | + if (!row.length || !col.length) return []; |
| 330 | + const ans = Array.from({ length: k }, () => new Array(k).fill(0)); |
| 331 | + const m = new Array(k + 1).fill(0); |
| 332 | + for (let i = 0; i < k; ++i) { |
| 333 | + m[col[i]] = i; |
| 334 | + } |
| 335 | + for (let i = 0; i < k; ++i) { |
| 336 | + ans[i][m[row[i]]] = row[i]; |
| 337 | + } |
| 338 | + return ans; |
| 339 | +} |
295 | 340 | ```
|
296 | 341 |
|
297 | 342 | ### **...**
|
|
0 commit comments