|
4 | 4 | * @param {number[][]} colConditions
|
5 | 5 | * @return {number[][]}
|
6 | 6 | */
|
7 |
| -var buildMatrix = function(k, rowConditions, colConditions) { |
8 |
| - const res = Array.from({ length: k }, () => Array(k).fill(0)); |
9 |
| - |
10 |
| - const row = khansAlgo(rowConditions, k); |
11 |
| - if(row.length!=k) return []; |
12 |
| - |
13 |
| - const col = khansAlgo(colConditions, k); |
14 |
| - if(col.length!=k) return []; |
15 |
| - |
16 |
| - const idx = Array(k+1).fill(0); |
17 |
| - for(let j=0;j<col.length;j++){ |
18 |
| - idx[col[j]] = j; |
19 |
| - } |
20 |
| - for(let i=0;i<k;i++){ |
21 |
| - res[i][idx[row[i]]] = row[i]; |
22 |
| - } |
23 |
| - return res; |
24 |
| - |
25 |
| - function khansAlgo(r, k){ |
26 |
| - const cnt = Array(k + 1).fill(0) |
27 |
| - const adj = Array.from({ length: k + 1}, () => Array()) |
| 7 | +var buildMatrix = function (k, rowConditions, colConditions) { |
| 8 | + const res = Array.from({ length: k }, () => Array(k).fill(0)) |
28 | 9 |
|
29 |
| - for(let x of r){ |
30 |
| - cnt[x[1]]++; |
31 |
| - adj[x[0]].push(x[1]); |
32 |
| - } |
33 |
| - const row = []; |
34 |
| - const q = []; |
35 |
| - for(let i=1;i<=k;i++){ |
36 |
| - if(cnt[i]==0){ |
37 |
| - q.push(i); |
38 |
| - } |
39 |
| - } |
40 |
| - while(q.length){ |
41 |
| - let t = q.pop(); |
42 |
| - |
43 |
| - row.push(t); |
44 |
| - for(let x of (adj[t] || [])) { |
45 |
| - cnt[x]--; |
46 |
| - if(cnt[x]==0){ |
47 |
| - q.push(x); |
48 |
| - } |
49 |
| - } |
| 10 | + const row = khansAlgo(rowConditions, k) |
| 11 | + if (row.length != k) return [] |
| 12 | + |
| 13 | + const col = khansAlgo(colConditions, k) |
| 14 | + if (col.length != k) return [] |
| 15 | + |
| 16 | + // console.log(row, col) |
| 17 | + const idx = Array(k + 1).fill(0) |
| 18 | + for (let j = 0; j < col.length; j++) { |
| 19 | + idx[col[j]] = j |
| 20 | + } |
| 21 | + for (let i = 0; i < k; i++) { |
| 22 | + res[i][idx[row[i]]] = row[i] |
| 23 | + } |
| 24 | + return res |
| 25 | + |
| 26 | + function khansAlgo(r, k) { |
| 27 | + const indegree = Array(k + 1).fill(0) |
| 28 | + const adj = Array.from({ length: k + 1 }, () => Array()) |
| 29 | + |
| 30 | + for (let x of r) { |
| 31 | + indegree[x[1]]++ |
| 32 | + adj[x[0]].push(x[1]) |
| 33 | + } |
| 34 | + const row = [] |
| 35 | + const q = [] |
| 36 | + for (let i = 1; i <= k; i++) { |
| 37 | + if (indegree[i] == 0) { |
| 38 | + q.push(i) |
| 39 | + } |
| 40 | + } |
| 41 | + while (q.length) { |
| 42 | + let t = q.pop() |
| 43 | + |
| 44 | + row.push(t) |
| 45 | + for (let x of adj[t] || []) { |
| 46 | + indegree[x]-- |
| 47 | + if (indegree[x] == 0) { |
| 48 | + q.push(x) |
50 | 49 | }
|
51 |
| - return row; |
| 50 | + } |
52 | 51 | }
|
53 |
| -}; |
| 52 | + return row |
| 53 | + } |
| 54 | +} |
| 55 | + |
54 | 56 |
|
55 | 57 | // another
|
56 | 58 |
|
|
0 commit comments