|
| 1 | +/** |
| 2 | + * @param {number[][]} grid |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +function largestIsland(grid) { |
| 6 | + const map = new Map() //Key: color, Val: size of island painted of that color |
| 7 | + map.set(0, 0) //We won't paint island 0, hence make its size 0, we will use this value later |
| 8 | + let n = grid.length |
| 9 | + let colorIndex = 2 //0 and 1 is already used in grid, hence we start colorIndex from 2 |
| 10 | + for (let i = 0; i < n; i++) { |
| 11 | + for (let j = 0; j < n; j++) { |
| 12 | + if (grid[i][j] == 1) { |
| 13 | + let size = paint(grid, i, j, colorIndex) |
| 14 | + map.set(colorIndex, size) |
| 15 | + colorIndex++ |
| 16 | + } |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + //If there is no island 0 from grid, res should be the size of islands of first color |
| 21 | + //If there is no island 1 from grid, res should be 0 |
| 22 | + let res = map.get(2) || 0 |
| 23 | + for (let i = 0; i < n; i++) { |
| 24 | + for (let j = 0; j < n; j++) { |
| 25 | + if (grid[i][j] === 0) { |
| 26 | + //We use a set to avoid repeatly adding islands with the same color |
| 27 | + const set = new Set() |
| 28 | + //If current island is at the boundary, we add 0 to the set, whose value is 0 in the map |
| 29 | + set.add(i > 0 ? grid[i - 1][j] : 0) |
| 30 | + set.add(i < n - 1 ? grid[i + 1][j] : 0) |
| 31 | + set.add(j > 0 ? grid[i][j - 1] : 0) |
| 32 | + set.add(j < n - 1 ? grid[i][j + 1] : 0) |
| 33 | + |
| 34 | + let newSize = 1 //We need to count current island as well, hence we init newSize with 1 |
| 35 | + for (let color of set) newSize += map.get(color) |
| 36 | + res = Math.max(res, newSize) |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + return res |
| 41 | +} |
| 42 | + |
| 43 | +//Helper method to paint current island and all its connected neighbors |
| 44 | +//Return the size of all painted islands at the end |
| 45 | +function paint(grid, i, j, color) { |
| 46 | + if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != 1) return 0 |
| 47 | + grid[i][j] = color |
| 48 | + return ( |
| 49 | + 1 + |
| 50 | + paint(grid, i + 1, j, color) + |
| 51 | + paint(grid, i - 1, j, color) + |
| 52 | + paint(grid, i, j + 1, color) + |
| 53 | + paint(grid, i, j - 1, color) |
| 54 | + ) |
| 55 | +} |
0 commit comments