|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | + |
| 4 | +class Solution { |
| 5 | + |
| 6 | + // TP: O(N*N) |
| 7 | + // SP: O(N*N) |
| 8 | + // pacific에 접하는 지점으로부터 dfs를 시작해 pacific에 도달할 수 있는 지점을 체크하고, |
| 9 | + // atlantic에 접하는 지점으로부터 dfs를 시작해 atlantic에 도달할 수 있는 지점을 체크한다. |
| 10 | + // 마지막으로 두 지점 모두에 도달할 수 있는 지점을 찾아 반환한다. |
| 11 | + int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; |
| 12 | + |
| 13 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 14 | + int rowSize = heights.length; |
| 15 | + int colSize = heights[0].length; |
| 16 | + |
| 17 | + boolean[][] pacific = new boolean[rowSize][colSize]; |
| 18 | + boolean[][] atlantic = new boolean[rowSize][colSize]; |
| 19 | + |
| 20 | + for (int i = 0; i < rowSize; i++) { |
| 21 | + dfs(i, 0, pacific, heights); |
| 22 | + dfs(i, colSize - 1, atlantic, heights); |
| 23 | + } |
| 24 | + |
| 25 | + for (int i = 0; i < colSize; i++) { |
| 26 | + dfs(0, i, pacific, heights); |
| 27 | + dfs(rowSize - 1, i, atlantic, heights); |
| 28 | + } |
| 29 | + |
| 30 | + List<List<Integer>> result = new ArrayList<>(); |
| 31 | + for (int i = 0; i < rowSize; i++) { |
| 32 | + for (int j = 0; j < colSize; j++) { |
| 33 | + if (pacific[i][j] && atlantic[i][j]) { |
| 34 | + result.add(List.of(i, j)); |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | + |
| 41 | + private void dfs(int row, int col, boolean[][] visited, int[][] heights) { |
| 42 | + visited[row][col] = true; |
| 43 | + |
| 44 | + for (int[] direction : directions) { |
| 45 | + int newRow = row + direction[0]; |
| 46 | + int newCol = col + direction[1]; |
| 47 | + |
| 48 | + if (newRow < 0 || newRow >= heights.length || newCol < 0 || newCol >= heights[0].length) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if (visited[newRow][newCol]) { |
| 53 | + continue; |
| 54 | + } |
| 55 | + |
| 56 | + if (heights[newRow][newCol] < heights[row][col]) { |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + dfs(newRow, newCol, visited, heights); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments