|
| 1 | +/** |
| 2 | + * ๋ฌธ์ ์ค๋ช
|
| 3 | + * - ๋น๊ฐ ๋ด๋ ธ์ ๋, ํํ์๊ณผ ๋์์ ๋ชจ๋๋ก ๋ฌผ์ด ํ๋ฅผ ์ ์๋ ์ง์ ์ ์ฐพ์ ๋ฐํํ๋ ๋ฌธ์ ์
๋๋ค. |
| 4 | + * ์์ด๋์ด |
| 5 | + * 1) BFS/DFS |
| 6 | + * - ๊ฐ ๋ฐ๋ค์์ ์ญ๋ฐฉํฅ์ผ๋ก ๋ฌผ์ด ๋๋ฌํ ์ ์๋ ์
์ ํ์ํ ํ, ๋ ๋ฐ๋ค ๋ชจ๋์ ๋๋ฌ ๊ฐ๋ฅํ ์
์ ๊ต์งํฉ ๊ตฌํ๊ธฐ |
| 7 | + * |
| 8 | + */ |
| 9 | + |
| 10 | +function pacificAtlantic(heights: number[][]): number[][] { |
| 11 | + const m = heights.length; |
| 12 | + const n = heights[0].length; |
| 13 | + |
| 14 | + const pacific = Array.from({ length: m }, () => Array(n).fill(false)); |
| 15 | + const atlantic = Array.from({ length: m }, () => Array(n).fill(false)); |
| 16 | + |
| 17 | + const directions = [ |
| 18 | + [1, 0], |
| 19 | + [-1, 0], |
| 20 | + [0, 1], |
| 21 | + [0, -1], |
| 22 | + ]; |
| 23 | + |
| 24 | + function dfs(r: number, c: number, visited: boolean[][], prevHeight: number) { |
| 25 | + if ( |
| 26 | + r < 0 || |
| 27 | + c < 0 || |
| 28 | + r >= m || |
| 29 | + c >= n || |
| 30 | + visited[r][c] || |
| 31 | + heights[r][c] < prevHeight |
| 32 | + ) |
| 33 | + return; |
| 34 | + |
| 35 | + visited[r][c] = true; |
| 36 | + |
| 37 | + for (const [dr, dc] of directions) { |
| 38 | + dfs(r + dr, c + dc, visited, heights[r][c]); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // ํํ์ DFS |
| 43 | + for (let i = 0; i < m; i++) { |
| 44 | + dfs(i, 0, pacific, heights[i][0]); // ์ผ์ชฝ |
| 45 | + dfs(i, n - 1, atlantic, heights[i][n - 1]); // ์ค๋ฅธ์ชฝ |
| 46 | + } |
| 47 | + |
| 48 | + for (let j = 0; j < n; j++) { |
| 49 | + dfs(0, j, pacific, heights[0][j]); // ์์ชฝ |
| 50 | + dfs(m - 1, j, atlantic, heights[m - 1][j]); // ์๋์ชฝ |
| 51 | + } |
| 52 | + |
| 53 | + const result: number[][] = []; |
| 54 | + |
| 55 | + for (let i = 0; i < m; i++) { |
| 56 | + for (let j = 0; j < n; j++) { |
| 57 | + if (pacific[i][j] && atlantic[i][j]) { |
| 58 | + result.push([i, j]); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return result; |
| 64 | +} |
0 commit comments