|
| 1 | +/* |
| 2 | +Time complexity : O(m * n) |
| 3 | +Space complexity : O(m * n) |
| 4 | +*/ |
| 5 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 6 | + const m = heights.length |
| 7 | + const n = heights[0].length |
| 8 | + const pacific: boolean[][] = Array(m).fill(null).map(() => Array(n).fill(false)) |
| 9 | + const atlantic: boolean[][] = Array(m).fill(null).map(() => Array(n).fill(false)) |
| 10 | + |
| 11 | + const dfs = (row: number, col: number, visited: boolean[][], prevH: number): void => { |
| 12 | + if (row < 0 || row >= m || col < 0 || col >= n || visited[row][col] || heights[row][col] < prevH) { |
| 13 | + return |
| 14 | + } |
| 15 | + visited[row][col] = true |
| 16 | + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] |
| 17 | + for (const [dr, dc] of directions) { |
| 18 | + dfs(row + dr, col + dc, visited, heights[row][col]) |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + for (let row = 0; row < m; row++) { |
| 23 | + dfs(row, 0, pacific, heights[row][0]) |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + for (let col = 0; col < n; col++) { |
| 28 | + dfs(0, col, pacific, heights[0][col]) |
| 29 | + } |
| 30 | + |
| 31 | + for (let row = 0; row < m; row++) { |
| 32 | + dfs(row, n - 1, atlantic, heights[row][n - 1]) |
| 33 | + } |
| 34 | + |
| 35 | + for (let col = 0; col < n; col++) { |
| 36 | + dfs(m - 1, col, atlantic, heights[m - 1][col]) |
| 37 | + } |
| 38 | + |
| 39 | + const result: number[][] = [] |
| 40 | + for (let row = 0; row < m; row++) { |
| 41 | + for (let col = 0; col < n; col++) { |
| 42 | + if (pacific[row][col] && atlantic[row][col]) { |
| 43 | + result.push([row, col]) |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return result |
| 48 | +}; |
0 commit comments