|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/number-of-islands |
| 3 | + * T.C. O(m*n) |
| 4 | + * S.C. O(m*n) |
| 5 | + */ |
| 6 | +// function numIslands(grid: string[][]): number { |
| 7 | +// let count = 0; |
| 8 | +// let dir = [[1, 0], [0, 1], [-1, 0], [0, -1]]; |
| 9 | + |
| 10 | +// function removeIsland(r: number, c: number) { |
| 11 | +// if (r < 0 || r >= grid.length) return; |
| 12 | +// if (c < 0 || c >= grid[0].length) return; |
| 13 | +// if (grid[r][c] === '0') return; |
| 14 | + |
| 15 | +// grid[r][c] = '0'; |
| 16 | +// for (let [dr, dc] of dir) { |
| 17 | +// removeIsland(r + dr, c + dc); |
| 18 | +// } |
| 19 | +// return 1; |
| 20 | +// } |
| 21 | + |
| 22 | +// for (let r = 0; r < grid.length; r++) { |
| 23 | +// for (let c = 0; c < grid[0].length; c++) { |
| 24 | +// if (grid[r][c] === '0') continue; |
| 25 | +// count++; |
| 26 | +// removeIsland(r, c); |
| 27 | +// } |
| 28 | +// } |
| 29 | + |
| 30 | +// return count; |
| 31 | +// } |
| 32 | + |
| 33 | +/** |
| 34 | + * T.C. O(m*n) |
| 35 | + * S.C. O(m*n) |
| 36 | + */ |
| 37 | +function numIslands(grid: string[][]): number { |
| 38 | + let count = 0; |
| 39 | + let dir = [[1, 0], [0, 1], [-1, 0], [0, -1]]; |
| 40 | + |
| 41 | + function removeIsland(r: number, c: number) { |
| 42 | + const stack = [[r, c]]; |
| 43 | + |
| 44 | + while (stack.length) { |
| 45 | + const [r, c] = stack.pop()!; |
| 46 | + if (r < 0 || r >= grid.length) continue; |
| 47 | + if (c < 0 || c >= grid[0].length) continue; |
| 48 | + if (grid[r][c] === '0') continue; |
| 49 | + |
| 50 | + grid[r][c] = '0'; |
| 51 | + for (let [dr, dc] of dir) { |
| 52 | + stack.push([r + dr, c + dc]); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + for (let r = 0; r < grid.length; r++) { |
| 58 | + for (let c = 0; c < grid[0].length; c++) { |
| 59 | + if (grid[r][c] === '0') continue; |
| 60 | + count++; |
| 61 | + removeIsland(r, c); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return count; |
| 66 | +} |
0 commit comments