1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| class Solution { private final int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public List<List<Integer>> pacificAtlantic(int[][] heights) { boolean[][] reachPacific = new boolean[heights.length][heights[0].length]; boolean[][] reachAtlantic = new boolean[heights.length][heights[0].length]; for (int i = 0; i < heights.length; i++) { reachPacific[i][0] = true; reachAtlantic[i][heights[0].length - 1] = true; }
for (int i = 0; i < heights[0].length; i++) { reachPacific[0][i] = true; reachAtlantic[heights.length - 1][i] = true; }
for (int i = 0; i < heights[0].length; i++) { dfs(0, i, reachPacific, heights); dfs(heights.length - 1, i, reachAtlantic, heights); } for (int i = 0; i < heights.length; i++) { dfs(i, 0, reachPacific, heights); dfs(i, heights[0].length - 1, reachAtlantic, heights); }
List<List<Integer>> ans = new ArrayList<>(); for (int row = 0; row < heights.length; row++) { for (int col = 0; col < heights[0].length; col++) { if (reachPacific[row][col] && reachAtlantic[row][col]) { ans.add(new ArrayList<>(Arrays.asList(row, col))); } } } return ans; }
private void dfs(int row, int col, boolean[][] reach, int[][] heights) { for (int[] direction : DIRECTIONS) { int x = row + direction[0]; int y = col + direction[1]; if (!isOutOfBound(heights, x, y) && !reach[x][y] && heights[x][y] >= heights[row][col]) { reach[x][y] = true; dfs(x, y, reach, heights); } } }
private boolean isOutOfBound(int[][] heights, int row, int col) { return row < 0 || row >= heights.length || col < 0 || col >= heights[0].length; } }
|