|
| 1 | +/** |
| 2 | + * @param {number[][]} grid |
| 3 | + * @param {number} stampHeight |
| 4 | + * @param {number} stampWidth |
| 5 | + * @return {boolean} |
| 6 | + */ |
| 7 | +var possibleToStamp = function(grid, stampHeight, stampWidth) { |
| 8 | + let d = []; |
| 9 | + let a = grid; |
| 10 | + let h = grid.length; |
| 11 | + let w = grid[0].length; |
| 12 | + for (let i = 0; i <= h; i++) { |
| 13 | + d[i] = new Array(w + 1).fill(0); |
| 14 | + } |
| 15 | + //d - height of empty cells below |
| 16 | + for (let i = h - 1; i >= 0; i--) { |
| 17 | + for (let j = 0; j < w; j++) { |
| 18 | + if (a[i][j] === 0) d[i][j] = d[i + 1][j] + 1; |
| 19 | + } |
| 20 | + } |
| 21 | + //find stamps, and start to fill matrix |
| 22 | + for (let i = 0; i < h; i++) { |
| 23 | + let columns = 0; //width of consecutive empty columns with height>=stampHeight |
| 24 | + for (let j = 0; j <= w; j++) { |
| 25 | + if (d[i][j] >= stampHeight) { //column can be part of stamp |
| 26 | + columns++; |
| 27 | + if (columns >= stampWidth) { |
| 28 | + //fill first row |
| 29 | + if (columns === stampWidth) { |
| 30 | + //fill previous columns |
| 31 | + for (let l = j - stampWidth + 1; l <= j; l++) { |
| 32 | + a[i][l] = stampHeight |
| 33 | + } |
| 34 | + } else { |
| 35 | + a[i][j] = stampHeight; |
| 36 | + } |
| 37 | + } |
| 38 | + } else { |
| 39 | + columns = 0; |
| 40 | + } |
| 41 | + } |
| 42 | + //fill cells below |
| 43 | + for (let l = 0; l < w; l++) { |
| 44 | + if (a[i][l] > 1) { |
| 45 | + a[i + 1][l] = a[i][l] - 1; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + //check if all cells covered |
| 51 | + let ans = true; |
| 52 | + for (let i = 0; i < h; i++) { |
| 53 | + for (let j = 0; j < w; j++) { |
| 54 | + if (a[i][j] === 0) ans = false; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return ans; |
| 59 | +}; |
0 commit comments