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