Given a binary grid where 1 is land and 0 is water, return the area of the largest island (4-directionally connected land). Return 0 if there is no island.
Same scan, but measure each island with a queue: count cells as they are dequeued and enqueue unvisited land neighbors.
1function maxAreaOfIsland(grid: number[][]): number {2const m = grid.length, n = grid[0].length;3let best = 0;4for (let r = 0; r < m; r++)5for (let c = 0; c < n; c++) {6if (grid[r][c] !== 1) continue;7grid[r][c] = 0;8const queue = [[r, c]];9let area = 0;10while (queue.length) {11const [i, j] = queue.shift()!; area++;12for (const [x, y] of [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]])13if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] === 1) { grid[x][y] = 0; queue.push([x, y]); }14}15best = Math.max(best, area);16}17return best;18}
| 1 | 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | 1 | 1 |
New island at (0, 0).
Space: play/pause · ←/→: step