|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + private int[][] heights; |
| 6 | + private int rows, cols; |
| 7 | + private int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; // ์ํ์ข์ฐ |
| 8 | + |
| 9 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 10 | + this.heights = heights; |
| 11 | + this.rows = heights.length; |
| 12 | + this.cols = heights[0].length; |
| 13 | + |
| 14 | + // ํํ์๊ณผ ๋์์์์ ๋๋ฌ ๊ฐ๋ฅํ ์ง์ ์ ์ ์ฅํ๋ ๋ฐฐ์ด |
| 15 | + boolean[][] pacific = new boolean[rows][cols]; |
| 16 | + boolean[][] atlantic = new boolean[rows][cols]; |
| 17 | + |
| 18 | + // ํํ์๊ณผ ๋์์ ๊ฒฝ๊ณ์์ ํ์ ์์ |
| 19 | + // ๋งจ ์์ค๊ณผ ๋งจ ์๋ซ์ค |
| 20 | + for (int j = 0; j < cols; j++) { |
| 21 | + dfs(0, j, pacific, Integer.MIN_VALUE); // ํํ์ (์์ค) |
| 22 | + dfs(rows - 1, j, atlantic, Integer.MIN_VALUE); // ๋์์ (์๋ซ์ค) |
| 23 | + } |
| 24 | + |
| 25 | + // ๋งจ ์ผ์ชฝ์ค๊ณผ ๋งจ ์ค๋ฅธ์ชฝ์ค |
| 26 | + for (int i = 0; i < rows; i++) { |
| 27 | + dfs(i, 0, pacific, Integer.MIN_VALUE); // ํํ์ (์ผ์ชฝ์ค) |
| 28 | + dfs(i, cols - 1, atlantic, Integer.MIN_VALUE); // ๋์์ (์ค๋ฅธ์ชฝ์ค) |
| 29 | + } |
| 30 | + |
| 31 | + // ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฆฌ์คํธ |
| 32 | + List<List<Integer>> result = new ArrayList<>(); |
| 33 | + |
| 34 | + // ์์ชฝ ๋ฐ๋ค๋ก ๋ชจ๋ ํ๋ฅผ ์ ์๋ ์ง์ ์ฐพ๊ธฐ |
| 35 | + for (int i = 0; i < rows; i++) { |
| 36 | + for (int j = 0; j < cols; j++) { |
| 37 | + if (pacific[i][j] && atlantic[i][j]) { |
| 38 | + List<Integer> coord = new ArrayList<>(); |
| 39 | + coord.add(i); |
| 40 | + coord.add(j); |
| 41 | + result.add(coord); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return result; |
| 47 | + } |
| 48 | + |
| 49 | + // ๊น์ด ์ฐ์ ํ์ (DFS) ํจ์ |
| 50 | + private void dfs(int r, int c, boolean[][] visited, int prevHeight) { |
| 51 | + // ์ ํจํ์ง ์์ ์ง์ (๋ฒ์ ๋ฐ, ์ด๋ฏธ ๋ฐฉ๋ฌธ, ๋์ด ์กฐ๊ฑด ๋ถ๋ง์กฑ) |
| 52 | + if (r < 0 || r >= rows || c < 0 || c >= cols || visited[r][c] || heights[r][c] < prevHeight) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + // ํ์ฌ ์ง์ ๋ฐฉ๋ฌธ ํ์ |
| 57 | + visited[r][c] = true; |
| 58 | + |
| 59 | + // ์ํ์ข์ฐ๋ก ํ์ ์งํ |
| 60 | + for (int[] dir : directions) { |
| 61 | + int newR = r + dir[0]; |
| 62 | + int newC = c + dir[1]; |
| 63 | + dfs(newR, newC, visited, heights[r][c]); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments