Skip to content

Commit 2367355

Browse files
authored
Update 2392-build-a-matrix-with-conditions.js
1 parent 23b830f commit 2367355

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

2392-build-a-matrix-with-conditions.js

+66
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,69 @@
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+
167
/**
268
* @param {number} k
369
* @param {number[][]} rowConditions

0 commit comments

Comments
 (0)