|
| 1 | +/** |
| 2 | + * 2132. Stamping the Grid |
| 3 | + * https://leetcode.com/problems/stamping-the-grid/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied). |
| 7 | + * |
| 8 | + * You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that |
| 9 | + * they follow the given restrictions and requirements: |
| 10 | + * 1. Cover all the empty cells. |
| 11 | + * 2. Do not cover any of the occupied cells. |
| 12 | + * 3. We can put as many stamps as we want. |
| 13 | + * 4. Stamps can overlap with each other. |
| 14 | + * 5. Stamps are not allowed to be rotated. |
| 15 | + * 6. Stamps must stay completely inside the grid. |
| 16 | + * |
| 17 | + * Return true if it is possible to fit the stamps while following the given restrictions and |
| 18 | + * requirements. Otherwise, return false. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[][]} grid |
| 23 | + * @param {number} stampHeight |
| 24 | + * @param {number} stampWidth |
| 25 | + * @return {boolean} |
| 26 | + */ |
| 27 | +var possibleToStamp = function(grid, stampHeight, stampWidth) { |
| 28 | + const rows = grid.length; |
| 29 | + const cols = grid[0].length; |
| 30 | + const prefixSum = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); |
| 31 | + const diff = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); |
| 32 | + |
| 33 | + for (let i = 0; i < rows; i++) { |
| 34 | + for (let j = 0; j < cols; j++) { |
| 35 | + prefixSum[i + 1][j + 1] = prefixSum[i + 1][j] + prefixSum[i][j + 1] |
| 36 | + - prefixSum[i][j] + grid[i][j]; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + for (let i = 0; i <= rows - stampHeight; i++) { |
| 41 | + for (let j = 0; j <= cols - stampWidth; j++) { |
| 42 | + const x = i + stampHeight; |
| 43 | + const y = j + stampWidth; |
| 44 | + if (prefixSum[x][y] - prefixSum[x][j] - prefixSum[i][y] + prefixSum[i][j] === 0) { |
| 45 | + diff[i][j]++; |
| 46 | + diff[i][y]--; |
| 47 | + diff[x][j]--; |
| 48 | + diff[x][y]++; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + const covered = new Array(rows).fill().map(() => new Array(cols).fill(0)); |
| 54 | + for (let i = 0; i < rows; i++) { |
| 55 | + for (let j = 0; j < cols; j++) { |
| 56 | + covered[i][j] = (i > 0 ? covered[i - 1][j] : 0) |
| 57 | + + (j > 0 ? covered[i][j - 1] : 0) |
| 58 | + - (i > 0 && j > 0 ? covered[i - 1][j - 1] : 0) + diff[i][j]; |
| 59 | + if (grid[i][j] === 0 && covered[i][j] === 0) return false; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return true; |
| 64 | +}; |
0 commit comments