|
| 1 | +/** |
| 2 | + * @link https://leetcode.com/problems/pacific-atlantic-water-flow/description/ |
| 3 | + * |
| 4 | + * ์ ๊ทผ ๋ฐฉ๋ฒ : |
| 5 | + * - pacific, atlantic๋ฅผ ๋์์ ๋๋ฌํ๋ ์ง์ ์ฐพ๊ธฐ ์ํด์, ๋๋ฌ ์ฌ๋ถ ํธ๋ํนํ๋ 2๊ฐ์ visited ๋ฐฐ์ด ์ฌ์ฉํ๋ค. |
| 6 | + * - ๋ฐ๋ค ๊ฒฝ๊ณ์์๋ง DFS๋ฅผ ํธ์ถํด์ ๋ฐฉ๋ฌธ ์ฌ๋ถ ์ฒดํฌํ๋ค. |
| 7 | + * - ๋ฐ๋ค ๊ฒฝ๊ณ์์ ์์ํ๊ธฐ ๋๋ฌธ์ DFS๋ ์ธ์ ์
์ ๋์ด๊ฐ ๊ฐ๊ฑฐ๋ ๋์ ๋๋ง ํธ์ถ๋์ด์ผ ํ๋ค. |
| 8 | + * |
| 9 | + * ์๊ฐ๋ณต์ก๋ : O(m * n) |
| 10 | + * - ๊ฐ ์
๋ง๋ค ์ต๋ 4๋ฒ DFS๊ฐ ํธ์ถ๋ ์ ์๋ค. O(m * n) |
| 11 | + * - ๊ฒฐ๊ณผ ์ํํ ๋ m * n ๋งํผ ์ํํ๋ค. |
| 12 | + * |
| 13 | + * ๊ณต๊ฐ๋ณต์ก๋ : O(m * n) |
| 14 | + * - 2๊ฐ์ visited ๋ฐฐ์ด ์ฌ์ฉํ๋ค. |
| 15 | + * - ์ต์
์ ๊ฒฝ์ฐ, m * n ๋ชจ๋ ์นธ์์ DFS ํธ์ถ๋๋ค. |
| 16 | + */ |
| 17 | + |
| 18 | +const directions = [ |
| 19 | + [-1, 0], |
| 20 | + [1, 0], |
| 21 | + [0, -1], |
| 22 | + [0, 1], |
| 23 | +]; |
| 24 | + |
| 25 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 26 | + const result: number[][] = []; |
| 27 | + |
| 28 | + const rows = heights.length; |
| 29 | + const cols = heights[0].length; |
| 30 | + |
| 31 | + // ๋ ๋ฐ๋ค ๋๋ฌํ๋ ์ง์ ํธ๋ํน ํ๊ธฐ ์ํ ๋ฐฐ์ด |
| 32 | + const pacificVisited = Array.from({ length: rows }, () => |
| 33 | + Array(cols).fill(false) |
| 34 | + ); |
| 35 | + const atlanticVisited = Array.from({ length: rows }, () => |
| 36 | + Array(cols).fill(false) |
| 37 | + ); |
| 38 | + |
| 39 | + const dfs = (row: number, col: number, visited: boolean[][]) => { |
| 40 | + if (visited[row][col]) return; |
| 41 | + // ๋ฐฉ๋ฌธ ์ง์ ๊ธฐ๋ก |
| 42 | + visited[row][col] = true; |
| 43 | + |
| 44 | + for (const [x, y] of directions) { |
| 45 | + const newRow = row + x; |
| 46 | + const newCol = col + y; |
| 47 | + |
| 48 | + // ์๋ก์ด ์์น๊ฐ ๊ฒฝ๊ณ์์ ์๊ณ , ํ์ฌ ๋์ด๋ณด๋ค ๊ฐ๊ฑฐ๋ ๋์ ๋๋ง DFS ํธ์ถ |
| 49 | + if ( |
| 50 | + 0 <= newRow && |
| 51 | + newRow < rows && |
| 52 | + 0 <= newCol && |
| 53 | + newCol < cols && |
| 54 | + heights[newRow][newCol] >= heights[row][col] |
| 55 | + ) |
| 56 | + dfs(newRow, newCol, visited); |
| 57 | + } |
| 58 | + }; |
| 59 | + |
| 60 | + // pacific ๊ฒฝ๊ณ์์ DFS ํธ์ถ (์ฒซ ๋ฒ์จฐ ์ด, ์ฒซ ๋ฒ์งธ ํ) |
| 61 | + for (let row = 0; row < rows; row++) dfs(row, 0, pacificVisited); |
| 62 | + for (let col = 0; col < cols; col++) dfs(0, col, pacificVisited); |
| 63 | + |
| 64 | + // atlantic ๊ฒฝ๊ณ์์ DFS ํธ์ถ (๋ง์ง๋ง ์ด, ๋ง์ง๋ง ํ) |
| 65 | + for (let row = 0; row < rows; row++) dfs(row, cols - 1, atlanticVisited); |
| 66 | + for (let col = 0; col < cols; col++) dfs(rows - 1, col, atlanticVisited); |
| 67 | + |
| 68 | + for (let row = 0; row < rows; row++) { |
| 69 | + for (let col = 0; col < cols; col++) { |
| 70 | + if (pacificVisited[row][col] && atlanticVisited[row][col]) |
| 71 | + result.push([row, col]); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return result; |
| 76 | +} |
0 commit comments