|
| 1 | +/* |
| 2 | + * time: O(M*N) |
| 3 | + * space: O(M*N) |
| 4 | + * - M is the number of rows |
| 5 | + * - N is the number of columns |
| 6 | + */ |
| 7 | +class Solution { |
| 8 | + |
| 9 | + int[][] heights; |
| 10 | + int rLen; |
| 11 | + int cLen; |
| 12 | + int[] rDirs = {0, -1, 0, 1}; |
| 13 | + int[] cDirs = {1, 0, -1, 0}; |
| 14 | + |
| 15 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 16 | + this.heights = heights; |
| 17 | + this.rLen = heights.length; |
| 18 | + this.cLen = heights[0].length; |
| 19 | + |
| 20 | + boolean[][] pacific = new boolean[rLen][cLen]; |
| 21 | + boolean[][] atlantic = new boolean[rLen][cLen]; |
| 22 | + |
| 23 | + for (int i = 0; i < rLen; i++) { |
| 24 | + dfs(i, 0, pacific); |
| 25 | + dfs(i, cLen - 1, atlantic); |
| 26 | + } |
| 27 | + |
| 28 | + for (int i = 0; i < cLen; i++) { |
| 29 | + dfs(0, i, pacific); |
| 30 | + dfs(rLen - 1, i, atlantic); |
| 31 | + } |
| 32 | + |
| 33 | + List<List<Integer>> both = new ArrayList<>(); |
| 34 | + for (int i = 0; i < rLen; i++) { |
| 35 | + for (int j = 0; j < cLen; j++) { |
| 36 | + if (pacific[i][j] && atlantic[i][j]) { |
| 37 | + both.add(List.of(i, j)); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return both; |
| 42 | + } |
| 43 | + |
| 44 | + private void dfs(int r, int c, boolean[][] visited) { |
| 45 | + visited[r][c] = true; |
| 46 | + |
| 47 | + for (int d = 0; d < 4; d++) { |
| 48 | + int nr = r + rDirs[d]; |
| 49 | + int nc = c + cDirs[d]; |
| 50 | + |
| 51 | + if (nr < 0 || nr > rLen - 1 || nc < 0 || nc > cLen - 1) { |
| 52 | + continue; |
| 53 | + } |
| 54 | + |
| 55 | + if (visited[nr][nc]) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + if (heights[nr][nc] < heights[r][c]) { |
| 60 | + continue; |
| 61 | + } |
| 62 | + |
| 63 | + dfs(nr, nc, visited); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments