|
| 1 | +// TC: O(n * m) |
| 2 | +// visit all elements |
| 3 | +// SC: O(n * m) |
| 4 | +// create result from all elements |
| 5 | +class Solution { |
| 6 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 7 | + List<List<Integer>> output = new ArrayList<>(); |
| 8 | + |
| 9 | + if (heights.length == 0 || heights[0].length == 0) return output; |
| 10 | + |
| 11 | + int rows = heights.length; |
| 12 | + int cols = heights[0].length; |
| 13 | + |
| 14 | + boolean[][] pac = new boolean[rows][cols]; |
| 15 | + boolean[][] atl = new boolean[rows][cols]; |
| 16 | + |
| 17 | + for (int j = 0; j < rows; j++) { |
| 18 | + dfs(j, 0, pac, heights[j][0], heights); |
| 19 | + dfs(j, cols-1, atl, heights[j][cols-1], heights); |
| 20 | + } |
| 21 | + |
| 22 | + for (int i = 0; i < cols; i++) { |
| 23 | + dfs(0, i, pac, heights[0][i], heights); |
| 24 | + dfs(rows-1, i, atl, heights[rows-1][i], heights); |
| 25 | + } |
| 26 | + |
| 27 | + for (int i = 0; i < rows; i++) { |
| 28 | + for (int j = 0; j < cols; j++) { |
| 29 | + if (pac[i][j] && atl[i][j]) output.add(List.of(i,j)); |
| 30 | + } |
| 31 | + } |
| 32 | + return output; |
| 33 | + } |
| 34 | + |
| 35 | + private void dfs(int i, int j, boolean[][] visit, int preValue, int[][] heights) { |
| 36 | + if (i < 0 || j < 0 || i == heights.length || j == heights[0].length || visit[i][j] || preValue > heights[i][j]) return; |
| 37 | + |
| 38 | + visit[i][j] = true; |
| 39 | + dfs(i + 1, j, visit, heights[i][j], heights); |
| 40 | + dfs(i - 1, j, visit, heights[i][j], heights); |
| 41 | + dfs(i, j + 1, visit, heights[i][j], heights); |
| 42 | + dfs(i, j - 1, visit, heights[i][j], heights); |
| 43 | + } |
| 44 | +} |
0 commit comments