|
| 1 | +/** |
| 2 | + * 1591. Strange Printer II |
| 3 | + * https://leetcode.com/problems/strange-printer-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a strange printer with the following two special requirements: |
| 7 | + * - On each turn, the printer will print a solid rectangular pattern of a single color on the |
| 8 | + * grid. This will cover up the existing colors in the rectangle. |
| 9 | + * - Once the printer has used a color for the above operation, the same color cannot be used again. |
| 10 | + * |
| 11 | + * You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position |
| 12 | + * (row, col) of the grid. |
| 13 | + * |
| 14 | + * Return true if it is possible to print the matrix targetGrid, otherwise, return false. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[][]} targetGrid |
| 19 | + * @return {boolean} |
| 20 | + */ |
| 21 | +var isPrintable = function(targetGrid) { |
| 22 | + const rows = targetGrid.length; |
| 23 | + const cols = targetGrid[0].length; |
| 24 | + const colorBounds = new Map(); |
| 25 | + |
| 26 | + for (let color = 1; color <= 60; color++) { |
| 27 | + let minRow = rows; |
| 28 | + let maxRow = -1; |
| 29 | + let minCol = cols; |
| 30 | + let maxCol = -1; |
| 31 | + |
| 32 | + for (let r = 0; r < rows; r++) { |
| 33 | + for (let c = 0; c < cols; c++) { |
| 34 | + if (targetGrid[r][c] === color) { |
| 35 | + minRow = Math.min(minRow, r); |
| 36 | + maxRow = Math.max(maxRow, r); |
| 37 | + minCol = Math.min(minCol, c); |
| 38 | + maxCol = Math.max(maxCol, c); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + if (maxRow >= 0) { |
| 43 | + colorBounds.set(color, [minRow, maxRow, minCol, maxCol]); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + const dependencies = new Map(); |
| 48 | + for (const [color, [minRow, maxRow, minCol, maxCol]] of colorBounds) { |
| 49 | + const deps = new Set(); |
| 50 | + for (let r = minRow; r <= maxRow; r++) { |
| 51 | + for (let c = minCol; c <= maxCol; c++) { |
| 52 | + if (targetGrid[r][c] !== color) { |
| 53 | + deps.add(targetGrid[r][c]); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + dependencies.set(color, deps); |
| 58 | + } |
| 59 | + |
| 60 | + const visited = new Set(); |
| 61 | + const recStack = new Set(); |
| 62 | + |
| 63 | + function hasCycle(color) { |
| 64 | + if (recStack.has(color)) return true; |
| 65 | + if (visited.has(color)) return false; |
| 66 | + |
| 67 | + visited.add(color); |
| 68 | + recStack.add(color); |
| 69 | + |
| 70 | + for (const dep of dependencies.get(color) || []) { |
| 71 | + if (hasCycle(dep)) return true; |
| 72 | + } |
| 73 | + |
| 74 | + recStack.delete(color); |
| 75 | + return false; |
| 76 | + } |
| 77 | + |
| 78 | + for (const color of colorBounds.keys()) { |
| 79 | + if (hasCycle(color)) return false; |
| 80 | + } |
| 81 | + |
| 82 | + return true; |
| 83 | +}; |
0 commit comments