|
| 1 | +/** |
| 2 | + * ๊น์ด ์ฐ์ ํ์(DFS)์ ์ฌ์ฉํ์ฌ ํน์ ๋ฐ๋ค์์ ์ฌ๋ผ๊ฐ ์ ์๋ ์ขํ์ ์ ์ฅ |
| 3 | + * @param i ํ์ฌ ์์น์ ํ (row) |
| 4 | + * @param j ํ์ฌ ์์น์ ์ด (column) |
| 5 | + * @param visited ๋ฐฉ๋ฌธํ ์ขํ๋ฅผ ์ ์ฅํ๋ Set (๋ฐ๋ค์์ ๋๋ฌํ ์ ์๋ ์์น๋ฅผ ์ ์ฅ) |
| 6 | + * @param heights ๋์ด ์ ๋ณด๊ฐ ๋ด๊ธด 2์ฐจ์ ๋ฐฐ์ด |
| 7 | + * |
| 8 | + * ์๊ฐ ๋ณต์ก๋: O(m ร n) |
| 9 | + * - ๊ฐ ์
์ ์ต๋ ํ ๋ฒ ๋ฐฉ๋ฌธํ๋ฉฐ, ์ด m ร n๊ฐ์ ์
์ ํ์ํจ |
| 10 | + * |
| 11 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(m ร n) |
| 12 | + * - `visited` Set์ ์ต๋ m ร n๊ฐ์ ์ขํ๋ฅผ ์ ์ฅ ๊ฐ๋ฅ |
| 13 | + * - ์ฌ๊ท ํธ์ถ ์คํ์ ๊น์ด๋ O(m + n) (์ต์
์ ๊ฒฝ์ฐ ๊ฐ์ฅ ๊ธด ๊ฒฝ๋ก๋ฅผ ๋ฐ๋ผ ํ์) |
| 14 | + */ |
| 15 | +function dfs(i: number, j: number, visited: Set<string>, heights: number[][]) { |
| 16 | + if (visited.has(`${i},${j}`)) return; |
| 17 | + |
| 18 | + visited.add(`${i},${j}`); |
| 19 | + |
| 20 | + for (const [di, dj] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) { |
| 21 | + const newI = i + di; |
| 22 | + const newJ = j + dj; |
| 23 | + |
| 24 | + if ( |
| 25 | + newI >= 0 && newI < heights.length && |
| 26 | + newJ >= 0 && newJ < heights[0].length && |
| 27 | + heights[newI][newJ] >= heights[i][j] |
| 28 | + ) { |
| 29 | + dfs(newI, newJ, visited, heights); |
| 30 | + } |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * ๋ ๋ฐ๋ค ๋ชจ๋ ๋๋ฌํ ์ ์๋ ์ขํ๋ฅผ ์ฐพ๋ ํจ์ |
| 36 | + * |
| 37 | + * @param heights 2์ฐจ์ ๋ฐฐ์ด๋ก ์ด๋ฃจ์ด์ง ์งํ์ ๋์ด ์ ๋ณด |
| 38 | + * @returns ๋ ๋ฐ๋ค ๋ชจ๋ ๋๋ฌํ ์ ์๋ ์ขํ ๋ฐฐ์ด |
| 39 | + * |
| 40 | + * ์๊ฐ ๋ณต์ก๋: O(m ร n) |
| 41 | + * - ํํ์ ๋ฐ ๋์์์์ ๊ฐ๊ฐ DFS ์ํ โ O(m ร n) |
| 42 | + * - ๊ฒฐ๊ณผ๋ฅผ ์ฐพ๋ ์ด์ค ๋ฃจํ โ O(m ร n) |
| 43 | + * |
| 44 | + * ๊ณต๊ฐ ๋ณต์ก๋: O(m ร n) |
| 45 | + * - `pacificSet`๊ณผ `atlanticSet`์ ์ต๋ O(m ร n)๊ฐ์ ์ขํ ์ ์ฅ |
| 46 | + * |
| 47 | + */ |
| 48 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 49 | + if (!heights || heights.length === 0 || heights[0].length === 0) return []; |
| 50 | + |
| 51 | + const rows = heights.length; |
| 52 | + const cols = heights[0].length; |
| 53 | + |
| 54 | + const pacificSet = new Set<string>(); |
| 55 | + const atlanticSet = new Set<string>(); |
| 56 | + |
| 57 | + // ํํ์(์ผ์ชฝ, ์์ชฝ)์์ ์ถ๋ฐํ๋ DFS |
| 58 | + for (let i = 0; i < rows; i++) dfs(i, 0, pacificSet, heights); |
| 59 | + for (let j = 0; j < cols; j++) dfs(0, j, pacificSet, heights); |
| 60 | + |
| 61 | + // ๋์์(์ค๋ฅธ์ชฝ, ์๋์ชฝ)์์ ์ถ๋ฐํ๋ DFS |
| 62 | + for (let i = 0; i < rows; i++) dfs(i, cols - 1, atlanticSet, heights); |
| 63 | + for (let j = 0; j < cols; j++) dfs(rows - 1, j, atlanticSet, heights); |
| 64 | + |
| 65 | + const result: number[][] = []; |
| 66 | + for (let i = 0; i < rows; i++) { |
| 67 | + for (let j = 0; j < cols; j++) { |
| 68 | + if (pacificSet.has(`${i},${j}`) && atlanticSet.has(`${i},${j}`)) { |
| 69 | + result.push([i, j]); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return result; |
| 75 | +}; |
| 76 | + |
0 commit comments