|
| 1 | +/** |
| 2 | + * [Problem]: [417] Pacific Atlantic Water Flow |
| 3 | + * (https://leetcode.com/problems/pacific-atlantic-water-flow/description/) |
| 4 | + */ |
| 5 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 6 | + //시간복잡도 O(n) |
| 7 | + //공간복잡도 O(n) |
| 8 | + const result: number[][] = []; |
| 9 | + const rows = heights.length; |
| 10 | + const cols = heights[0].length; |
| 11 | + |
| 12 | + const pacificArea: boolean[][] = Array.from({ length: rows }, () => Array(cols).fill(false)); |
| 13 | + const atlanticArea: boolean[][] = Array.from({ length: rows }, () => Array(cols).fill(false)); |
| 14 | + |
| 15 | + function dfs(visited: boolean[][], row: number, col: number) { |
| 16 | + if (row < 0 || col < 0 || row >= rows || col >= cols) return; |
| 17 | + if (visited[row][col]) return; |
| 18 | + |
| 19 | + visited[row][col] = true; |
| 20 | + |
| 21 | + [ |
| 22 | + [row - 1, col], |
| 23 | + [row + 1, col], |
| 24 | + [row, col - 1], |
| 25 | + [row, col + 1], |
| 26 | + ].forEach(([r, c]) => { |
| 27 | + if (r >= 0 && c >= 0 && r < rows && c < cols) { |
| 28 | + if (heights[r][c] >= heights[row][col]) { |
| 29 | + dfs(visited, r, c); |
| 30 | + } |
| 31 | + } |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + for (let i = 0; i < rows; i++) { |
| 36 | + dfs(pacificArea, i, 0); |
| 37 | + dfs(atlanticArea, i, cols - 1); |
| 38 | + } |
| 39 | + for (let j = 0; j < cols; j++) { |
| 40 | + dfs(pacificArea, 0, j); |
| 41 | + dfs(atlanticArea, rows - 1, j); |
| 42 | + } |
| 43 | + |
| 44 | + for (let i = 0; i < rows; i++) { |
| 45 | + for (let j = 0; j < cols; j++) { |
| 46 | + if (pacificArea[i][j] && atlanticArea[i][j]) { |
| 47 | + result.push([i, j]); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return result; |
| 53 | +} |
0 commit comments