Skip to content

Commit 6405532

Browse files
authored
Update 1591-strange-printer-ii.js
1 parent ee5ed07 commit 6405532

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

1591-strange-printer-ii.js

+68
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,71 @@
1+
/**
2+
* @param {number[][]} targetGrid
3+
* @return {boolean}
4+
*/
5+
const isPrintable = function(targetGrid) {
6+
// solve the problem: BFS
7+
// 1. find the top-left and bottom-right corner of each color
8+
// 2. check if there is a circle in the graph
9+
// 3. if there is a circle, return false
10+
// 4. if there is no circle, return true
11+
const m = targetGrid.length;
12+
const n = targetGrid[0].length;
13+
const left = new Array(61).fill(n);
14+
const right = new Array(61).fill(-1);
15+
const top = new Array(61).fill(m);
16+
const bottom = new Array(61).fill(-1);
17+
const next = new Array(61).fill(null).map(() => []);
18+
for (let i = 0; i < m; i++) {
19+
for (let j = 0; j < n; j++) {
20+
const color = targetGrid[i][j];
21+
left[color] = Math.min(left[color], j);
22+
right[color] = Math.max(right[color], j);
23+
top[color] = Math.min(top[color], i);
24+
bottom[color] = Math.max(bottom[color], i);
25+
}
26+
}
27+
for (let i = 0; i < m; i++) {
28+
for (let j = 0; j < n; j++) {
29+
for (let color = 1; color <= 60; color++) {
30+
if (i >= top[color] && i <= bottom[color] && j >= left[color] && j <= right[color]) {
31+
if (color !== targetGrid[i][j]) {
32+
next[targetGrid[i][j]].push(color);
33+
}
34+
}
35+
}
36+
}
37+
}
38+
const numNodes = 61;
39+
const inDegree = new Array(numNodes).fill(0);
40+
for (let i = 0; i < numNodes; i++) {
41+
for (const j of next[i]) {
42+
inDegree[j]++;
43+
}
44+
}
45+
const queue = [];
46+
let count = 0;
47+
for (let i = 0; i < numNodes; i++) {
48+
if (inDegree[i] === 0) {
49+
queue.push(i);
50+
count++;
51+
}
52+
}
53+
while (queue.length > 0) {
54+
const curCourse = queue.shift();
55+
for (const child of next[curCourse]) {
56+
inDegree[child]--;
57+
if (inDegree[child] === 0) {
58+
queue.push(child);
59+
count++;
60+
}
61+
}
62+
}
63+
return count === numNodes;
64+
};
65+
66+
// another
67+
68+
169
/**
270
* @param {number[][]} targetGrid
371
* @return {boolean}

0 commit comments

Comments
 (0)