Skip to content

Commit 2e89930

Browse files
authored
Update 2392-build-a-matrix-with-conditions.js
1 parent 6e6292d commit 2e89930

File tree

1 file changed

+46
-44
lines changed

1 file changed

+46
-44
lines changed

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

+46-44
Original file line numberDiff line numberDiff line change
@@ -4,53 +4,55 @@
44
* @param {number[][]} colConditions
55
* @return {number[][]}
66
*/
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))
289

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)
5049
}
51-
return row;
50+
}
5251
}
53-
};
52+
return row
53+
}
54+
}
55+
5456

5557
// another
5658

0 commit comments

Comments
 (0)