|
| 1 | +/** |
| 2 | + * 764. Largest Plus Sign |
| 3 | + * https://leetcode.com/problems/largest-plus-sign/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer n. You have an n x n binary grid grid with all values initially |
| 7 | + * 1's except for some indices given in the array mines. The ith element of the array mines |
| 8 | + * is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0. |
| 9 | + * |
| 10 | + * Return the order of the largest axis-aligned plus sign of 1's contained in grid. If |
| 11 | + * there is none, return 0. |
| 12 | + * |
| 13 | + * An axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four |
| 14 | + * arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could |
| 15 | + * be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is |
| 16 | + * checked for 1's. |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} n |
| 21 | + * @param {number[][]} mines |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +function orderOfLargestPlusSign(n, mines) { |
| 25 | + const grid = Array(n).fill().map(() => Array(n).fill(1)); |
| 26 | + mines.forEach(([x, y]) => grid[x][y] = 0); |
| 27 | + |
| 28 | + const left = Array(n).fill().map(() => Array(n).fill(0)); |
| 29 | + const right = Array(n).fill().map(() => Array(n).fill(0)); |
| 30 | + const up = Array(n).fill().map(() => Array(n).fill(0)); |
| 31 | + const down = Array(n).fill().map(() => Array(n).fill(0)); |
| 32 | + |
| 33 | + for (let i = 0; i < n; i++) { |
| 34 | + for (let j = 0; j < n; j++) { |
| 35 | + left[i][j] = grid[i][j] ? (j > 0 ? left[i][j-1] + 1 : 1) : 0; |
| 36 | + up[i][j] = grid[i][j] ? (i > 0 ? up[i-1][j] + 1 : 1) : 0; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + for (let i = n - 1; i >= 0; i--) { |
| 41 | + for (let j = n - 1; j >= 0; j--) { |
| 42 | + right[i][j] = grid[i][j] ? (j < n-1 ? right[i][j+1] + 1 : 1) : 0; |
| 43 | + down[i][j] = grid[i][j] ? (i < n-1 ? down[i+1][j] + 1 : 1) : 0; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + let maxOrder = 0; |
| 48 | + for (let i = 0; i < n; i++) { |
| 49 | + for (let j = 0; j < n; j++) { |
| 50 | + maxOrder = Math.max( |
| 51 | + maxOrder, |
| 52 | + Math.min(left[i][j], right[i][j], up[i][j], down[i][j]) |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return maxOrder; |
| 58 | +} |
0 commit comments