Skip to content

Commit 095007b

Browse files
authored
Update 2392-build-a-matrix-with-conditions.js
1 parent 473f1d0 commit 095007b

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

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

+56
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1+
/**
2+
* @param {number} k
3+
* @param {number[][]} rowConditions
4+
* @param {number[][]} colConditions
5+
* @return {number[][]}
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())
28+
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+
}
50+
}
51+
return row;
52+
}
53+
};
54+
55+
// another
56+
157
/**
258
* @param {number} k
359
* @param {number[][]} rowConditions

0 commit comments

Comments
 (0)