Given a grid of '1' (land) and '0' (water), return the number of islands: groups of land connected horizontally or vertically.
Start with one set per land cell. Union each land cell with its land neighbors to the right and below. Every successful union merges two islands, so subtract one.
1function numIslands(grid: string[][]): number {2const m = grid.length, n = grid[0].length, parent: number[] = [];3let count = 0;4const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));5for (let r = 0; r < m; r++) for (let c = 0; c < n; c++)6if (grid[r][c] === "1") { parent[r * n + c] = r * n + c; count++; }7for (let r = 0; r < m; r++) for (let c = 0; c < n; c++) {8if (grid[r][c] !== "1") continue;9for (const [x, y] of [[r + 1, c], [r, c + 1]]) {10if (x >= m || y >= n || grid[x][y] !== "1") continue;11const a = find(r * n + c), b = find(x * n + y);12if (a !== b) { parent[a] = b; count--; }13}14}15return count;16}
| 0 | 1 | |||
| 5 | 6 | |||
| 12 | ||||
| 18 | 19 |
Each of the 7 land cells is its own set.
Space: play/pause · ←/→: step