|
| 1 | +/** |
| 2 | + * 695. Max Area of Island |
| 3 | + * https://leetcode.com/problems/max-area-of-island/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n binary matrix grid. An island is a group of 1's (representing land) |
| 7 | + * connected 4-directionally (horizontal or vertical.) You may assume all four edges of the |
| 8 | + * grid are surrounded by water. |
| 9 | + * |
| 10 | + * The area of an island is the number of cells with a value 1 in the island. |
| 11 | + * |
| 12 | + * Return the maximum area of an island in grid. If there is no island, return 0. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[][]} grid |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var maxAreaOfIsland = function(grid) { |
| 20 | + const cache = new Set(); |
| 21 | + let max = 0; |
| 22 | + |
| 23 | + for (let i = 0; i < grid.length; i++) { |
| 24 | + for (let j = 0; j < grid[0].length; j++) { |
| 25 | + max = Math.max(max, traverse(grid, cache, i, j)); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + return max; |
| 30 | +}; |
| 31 | + |
| 32 | +function traverse(grid, cache, x, y) { |
| 33 | + let count = 0; |
| 34 | + if (grid[x] && grid[x][y] === 1 && !cache.has(`${x},${y}`)) { |
| 35 | + cache.add(`${x},${y}`); |
| 36 | + count += [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]] |
| 37 | + .map(([x, y]) => traverse(grid, cache, x, y)) |
| 38 | + .reduce((sum, count) => sum + count, 0) + 1; |
| 39 | + } |
| 40 | + return count; |
| 41 | +} |
0 commit comments