|
| 1 | +/** |
| 2 | + * @param {number} k |
| 3 | + * @param {number[][]} rowConditions |
| 4 | + * @param {number[][]} colConditions |
| 5 | + * @return {number[][]} |
| 6 | + */ |
| 7 | +const buildMatrix = function(k, rowConditions, colConditions) { |
| 8 | + const col = topo(k, colConditions); |
| 9 | + const row = topo(k, rowConditions); |
| 10 | + if(col.length === 0 || row.length === 0) return [] |
| 11 | + |
| 12 | + const res = Array.from({length: k}, () => Array.from({length: k}, () => 0)); |
| 13 | + const colHash = {}, rowHash = {}; |
| 14 | + for(let i = 0; i < k; i++) { |
| 15 | + colHash[col[i]] = i; |
| 16 | + rowHash[row[i]] = i; |
| 17 | + } |
| 18 | + for(let i = 1; i <= k; i++) { |
| 19 | + res[rowHash[i]][colHash[i]] = i |
| 20 | + } |
| 21 | + |
| 22 | + return res |
| 23 | + |
| 24 | + function topo(k, conditions) { |
| 25 | + const n = conditions.length; |
| 26 | + const ind = new Array(k + 1).fill(0); |
| 27 | + const adj = Array.from({length: k + 1}, () => []); |
| 28 | + for(let i = 0; i < n; i++) { |
| 29 | + const [a, b] = conditions[i]; |
| 30 | + adj[a].push(b); |
| 31 | + ind[b]++; |
| 32 | + } |
| 33 | + // console.log(adj, ind) |
| 34 | + let q = [] |
| 35 | + for(let i = 1; i <= k; i++) { |
| 36 | + if (ind[i] === 0) { |
| 37 | + q.push(i); |
| 38 | + } |
| 39 | + } |
| 40 | + const res = [] |
| 41 | + |
| 42 | + while(q.length) { |
| 43 | + const size = q.length |
| 44 | + const tmp = [] |
| 45 | + for(let i = 0; i < size; i++) { |
| 46 | + |
| 47 | + const node = q[i] |
| 48 | + res.push(node) |
| 49 | + for(const nxt of adj[node]) { |
| 50 | + ind[nxt]--; |
| 51 | + if (ind[nxt] === 0) { |
| 52 | + tmp.push(nxt); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + q = tmp |
| 57 | + } |
| 58 | + // console.log(res) |
| 59 | + if(res.length !== k) return [] |
| 60 | + return res |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | +// another |
| 65 | + |
| 66 | + |
1 | 67 | /**
|
2 | 68 | * @param {number} k
|
3 | 69 | * @param {number[][]} rowConditions
|
|
0 commit comments