|
| 1 | +class Solution { |
| 2 | + int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; |
| 3 | + public List<List<Integer>> pacificAtlantic(int[][] heights) { |
| 4 | + List<List<Integer>> res = new ArrayList<>(); |
| 5 | + |
| 6 | + int rows = heights.length, cols = heights[0].length; |
| 7 | + boolean[][] pacific = new boolean[rows][cols]; |
| 8 | + boolean[][] atlantic = new boolean[rows][cols]; |
| 9 | + |
| 10 | + for (int i = 0; i < cols; i++) { |
| 11 | + dfs(heights, 0, i, Integer.MIN_VALUE, pacific); |
| 12 | + dfs(heights, rows - 1, i, Integer.MIN_VALUE, atlantic); |
| 13 | + } |
| 14 | + |
| 15 | + for (int i = 0; i < rows; i++) { |
| 16 | + dfs(heights, i, 0, Integer.MIN_VALUE, pacific); |
| 17 | + dfs(heights, i, cols - 1, Integer.MIN_VALUE, atlantic); |
| 18 | + } |
| 19 | + |
| 20 | + for (int i = 0; i < rows; i++) { |
| 21 | + for (int j = 0; j < cols; j++) { |
| 22 | + if (pacific[i][j] && atlantic[i][j]) { |
| 23 | + res.add(Arrays.asList(i, j)); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + return res; |
| 28 | + } |
| 29 | + |
| 30 | + private void dfs(int[][] heights, int i, int j, int prev, boolean[][] ocean) { |
| 31 | + if (i < 0 || i >= ocean.length || j < 0 || j >= ocean[0].length) return; |
| 32 | + if (heights[i][j] < prev || ocean[i][j]) return; |
| 33 | + |
| 34 | + ocean[i][j] = true; |
| 35 | + for (int[] d: dir) { |
| 36 | + dfs(heights, i + d[0], j + d[1], heights[i][j], ocean); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
0 commit comments