|
| 1 | +// TC: O(m * n) |
| 2 | +// SC: O(m * n) |
| 3 | + |
| 4 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 5 | + const m = heights.length; |
| 6 | + const n = heights[0].length; |
| 7 | + |
| 8 | + const pacific: boolean[][] = Array.from({ length: m }, () => |
| 9 | + Array(n).fill(false) |
| 10 | + ); |
| 11 | + const atlantic: boolean[][] = Array.from({ length: m }, () => |
| 12 | + Array(n).fill(false) |
| 13 | + ); |
| 14 | + |
| 15 | + const directions = [ |
| 16 | + [0, 1], |
| 17 | + [0, -1], |
| 18 | + [1, 0], |
| 19 | + [-1, 0], |
| 20 | + ]; |
| 21 | + |
| 22 | + const dfs = (row: number, col: number, visited: boolean[][]) => { |
| 23 | + visited[row][col] = true; |
| 24 | + // Border cells are adjacent to the ocean, so they are marked as reachable (true) |
| 25 | + |
| 26 | + // From each ocean-border cell, we explore inward: |
| 27 | + // if an adjacent cell is higher or equal, water can flow from it to the ocean |
| 28 | + // → mark it as reachable (true) |
| 29 | + for (const [dr, dc] of directions) { |
| 30 | + const newRow = row + dr; |
| 31 | + const newCol = col + dc; |
| 32 | + |
| 33 | + if ( |
| 34 | + newRow >= 0 && |
| 35 | + newRow < m && |
| 36 | + newCol >= 0 && |
| 37 | + newCol < n && |
| 38 | + !visited[newRow][newCol] && |
| 39 | + heights[row][col] <= heights[newRow][newCol] |
| 40 | + // heights[row][col] <= heights[newRow][newCol] |
| 41 | + // → Water can flow from (newRow, newCol) to (row, col), |
| 42 | + // so (row, col) is reachable from the ocean through (newRow, newCol) |
| 43 | + ) { |
| 44 | + dfs(newRow, newCol, visited); |
| 45 | + } |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + for (let i = 0; i < m; i++) { |
| 50 | + dfs(i, 0, pacific); |
| 51 | + dfs(i, n - 1, atlantic); |
| 52 | + } |
| 53 | + |
| 54 | + for (let j = 0; j < n; j++) { |
| 55 | + dfs(0, j, pacific); |
| 56 | + dfs(m - 1, j, atlantic); |
| 57 | + } |
| 58 | + |
| 59 | + let result: number[][] = []; |
| 60 | + |
| 61 | + for (let i = 0; i < m; i++) { |
| 62 | + for (let j = 0; j < n; j++) { |
| 63 | + if (pacific[i][j] && atlantic[i][j]) { |
| 64 | + result.push([i, j]); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return result; |
| 70 | +} |
| 71 | + |
0 commit comments