|
| 1 | +/** |
| 2 | + Let's iteration and check their adjacency node if they are both '1' |
| 3 | + 1. Iteration from [0,0] to [m,n] |
| 4 | + 2. For [i,j], if it's '1' check the [i+1,j] [i,j+1] |
| 5 | + 1. if yes, then union(find(i,j), find(i+1,j)) |
| 6 | + 3. Before access the arry, notice the corner case |
| 7 | + |
| 8 | + Let's define the union/find structure |
| 9 | + 1. mxn table |
| 10 | + 2. find(i,j) |
| 11 | + 1. if(table[i][j] is empty then table[i][j] = [i,j]; |
| 12 | + 1. generateId: just increase the unique key |
| 13 | + 2. else return find(table[i][j]) |
| 14 | + 3. union(a,b) |
| 15 | + 1. find(a) = find(b); |
| 16 | +**/ |
| 17 | + |
| 18 | +function numIslands(grid: string[][]): number { |
| 19 | + const m = grid.length; |
| 20 | + const n = grid[0].length; |
| 21 | + |
| 22 | + const parent: number[][][] = Array.from({ length: m }, (val) => |
| 23 | + Array.from({ length: n }, (val) => [-1, -1]) |
| 24 | + ); |
| 25 | + |
| 26 | + const find = (...u: number[]): number[] => { |
| 27 | + const [i, j] = u; |
| 28 | + const [pI, pJ] = parent[i][j]; |
| 29 | + if (pI === -1 && pJ === -1) { |
| 30 | + parent[i][j] = [i, j]; |
| 31 | + return [i, j]; |
| 32 | + } else { |
| 33 | + return pI === i && pJ === j ? [i, j] : find(pI, pJ); |
| 34 | + } |
| 35 | + }; |
| 36 | + const union = (u1: number[], u2: number[]): void => { |
| 37 | + console.log(u1, u2); |
| 38 | + const p1 = find(...u1); |
| 39 | + const [i, j] = find(...u2); |
| 40 | + parent[i][j] = p1; |
| 41 | + }; |
| 42 | + |
| 43 | + for (let i = 0; i < m; i++) { |
| 44 | + for (let j = 0; j < n; j++) { |
| 45 | + if (grid[i][j] === "0") continue; |
| 46 | + if (i + 1 !== m && j + 1 !== n && grid[i + 1][j + 1] === "1") |
| 47 | + union([i, j], [i + 1, j + 1]); |
| 48 | + if (i + 1 !== m && grid[i + 1][j] === "1") union([i, j], [i + 1, j]); |
| 49 | + if (j + 1 !== n && grid[i][j + 1] === "1") union([i, j], [i, j + 1]); |
| 50 | + } |
| 51 | + } |
| 52 | + const collections: Set<string> = new Set(); |
| 53 | + for (let i = 0; i < m; i++) { |
| 54 | + for (let j = 0; j < n; j++) { |
| 55 | + const p = parent[i][j]; |
| 56 | + if (p[0] === -1 && p[1] === -1) continue; |
| 57 | + collections.add(`${p[0]}-${p[1]}`); |
| 58 | + } |
| 59 | + } |
| 60 | + return collections.size; |
| 61 | +} |
0 commit comments