|
| 1 | +/** |
| 2 | + * 827. Making A Large Island |
| 3 | + * https://leetcode.com/problems/making-a-large-island/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. |
| 7 | + * |
| 8 | + * Return the size of the largest island in grid after applying this operation. |
| 9 | + * |
| 10 | + * An island is a 4-directionally connected group of 1s. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} grid |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +var largestIsland = function(grid) { |
| 18 | + function traverse(tile, grid, i, j) { |
| 19 | + if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length |
| 20 | + || grid[i][j] === 0 || grid[i][j] === tile) { |
| 21 | + return 0; |
| 22 | + } |
| 23 | + grid[i][j] = tile; |
| 24 | + return 1 + ( |
| 25 | + traverse(tile, grid, i + 1, j) |
| 26 | + + traverse(tile, grid, i - 1, j) |
| 27 | + + traverse(tile, grid, i, j + 1) |
| 28 | + + traverse(tile, grid, i, j - 1) |
| 29 | + ); |
| 30 | + }; |
| 31 | + |
| 32 | + const map = new Map(); |
| 33 | + let tile = 2; |
| 34 | + let result = -1; |
| 35 | + |
| 36 | + for (let i = 0; i < grid.length; i++) { |
| 37 | + for (let j = 0; j < grid.length; j++) { |
| 38 | + if (grid[i][j] === 1) { |
| 39 | + const value = traverse(tile, grid, i, j); |
| 40 | + map.set(tile, value); |
| 41 | + tile += 1; |
| 42 | + result = Math.max(result, value); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + map.set(0, 0); |
| 48 | + |
| 49 | + for (let i = 0; i < grid.length; i++) { |
| 50 | + for (let j = 0; j < grid.length; j++) { |
| 51 | + if (!grid[i][j]) { |
| 52 | + const seen = new Set(); |
| 53 | + let sum = 0; |
| 54 | + if (i > 0) seen.add(grid[i - 1][j]); |
| 55 | + if (j > 0) seen.add(grid[i][j - 1]); |
| 56 | + if (i < grid.length - 1) seen.add(grid[i + 1][j]); |
| 57 | + if (j < grid.length - 1) seen.add(grid[i][j + 1]); |
| 58 | + seen.forEach(val => sum += map.get(val)); |
| 59 | + result = Math.max(result, sum + 1); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return result; |
| 65 | +}; |
0 commit comments