|
| 1 | +/** |
| 2 | + * @param {number[][]} heights |
| 3 | + * @return {number[][]} |
| 4 | + */ |
| 5 | +const pacificAtlantic = function (heights) { |
| 6 | + // ๊ฐ cell์์ ์์ํด์ ๋ฐ๋ค๋ก ๋ป์ด๋๊ฐ๋ ๊ฒ ๋ง๊ณ |
| 7 | + // ๋ฐ๋ค์์ ์์ํด์ ๊ฐ cell์ด ๋ฐ๋ค๋ก ํ๋ฌ์ฌ ์ ์๋์ง ํ์ธํ ํ |
| 8 | + // ๋ ๋ฐ๋ค์ ๋ชจ๋ ํ๋ฌ๊ฐ ์ ์๋ cell๋ง filter |
| 9 | + |
| 10 | + const rows = heights.length; |
| 11 | + const cols = heights[0].length; |
| 12 | + |
| 13 | + // ๊ฐ ๋ฐ๋ค์ ๋๋ฌ ๊ฐ๋ฅํ์ง ์ฌ๋ถ๋ฅผ ๋ด๋ visited๋ฅผ ๋ง๋ฆ |
| 14 | + const pacific = Array.from({ length: rows }, () => Array(cols).fill(false)); |
| 15 | + const atlantic = Array.from({ length: rows }, () => Array(cols).fill(false)); |
| 16 | + |
| 17 | + const direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]; |
| 18 | + |
| 19 | + // ์ํ |
| 20 | + function bfs(r, c, visited) { |
| 21 | + visited[r][c] = true; |
| 22 | + |
| 23 | + const queue = [[r, c]]; |
| 24 | + |
| 25 | + while (queue.length) { |
| 26 | + const [r, c] = queue.shift(); |
| 27 | + |
| 28 | + for (const [dr, dc] of direction) { |
| 29 | + const nr = r + dr; |
| 30 | + const nc = c + dc; |
| 31 | + |
| 32 | + // ๋๋ณด๋ค height๊ฐ ํฌ๊ณ , ๋ฐฉ๋ฌธํ ์ ์์ผ๋ฉด, ํ์ ๋ด๊ธฐ |
| 33 | + if (0 <= nr && nr < rows && 0 <= nc && nc < cols |
| 34 | + && !visited[nr][nc] |
| 35 | + && heights[nr][nc] >= heights[r][c] |
| 36 | + ) { |
| 37 | + queue.push([nr, nc]); |
| 38 | + visited[nr][nc] = true; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // ๋ฐ๋ค์์ ์์ํด์ ๊ฑฐ๊พธ๋ก ํ์ |
| 45 | + for (let r = 0; r < rows; r++) { |
| 46 | + bfs(r, 0, pacific); // left |
| 47 | + bfs(r, cols - 1, atlantic); // right |
| 48 | + } |
| 49 | + |
| 50 | + for (let c = 0; c < cols; c++) { |
| 51 | + bfs(0, c, pacific); // top |
| 52 | + bfs(rows - 1, c, atlantic); // bottom |
| 53 | + } |
| 54 | + |
| 55 | + // ํํ์, ๋์์์ผ๋ก ๋ชจ๋ flowํ ์ ์๋ cell ์ฐพ๊ธฐ |
| 56 | + const result = []; |
| 57 | + |
| 58 | + for (let r = 0; r < rows; r++) { |
| 59 | + for (let c = 0; c < cols; c++) { |
| 60 | + if (pacific[r][c] && atlantic[r][c]) { |
| 61 | + result.push([r, c]); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return result; |
| 67 | +}; |
| 68 | + |
| 69 | +// ์๊ฐ๋ณต์ก๋: O(m*n) |
| 70 | +// ๊ณต๊ฐ๋ณต์ก๋: O(m*n) |
0 commit comments