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
| class Solution { public List<List<Integer>> pacificAtlantic(int[][] heights) { List<List<Integer>> resultList = new ArrayList<>();
int m = heights.length, n = heights[0].length; boolean[][] pacific = new boolean[m][n]; boolean[][] atlantic = new boolean[m][n];
for (int i = 0; i < m; i++) { dfs(heights, pacific, i, 0, m, n); dfs(heights, atlantic, i, n - 1, m, n); } for (int j = 0; j < n; j++) { dfs(heights, pacific, 0, j, m, n); dfs(heights, atlantic, m - 1, j, m, n); }
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (pacific[i][j] && atlantic[i][j]) { resultList.add(Arrays.asList(i, j)); } } }
return resultList; }
private void dfs(int[][] heights, boolean[][] flags, int i, int j, int m, int n) { if (flags[i][j]) { return; }
flags[i][j] = true; if (i > 0 && heights[i - 1][j] >= heights[i][j]) { dfs(heights, flags, i - 1, j, m, n); } if (i < m - 1 && heights[i + 1][j] >= heights[i][j]) { dfs(heights, flags, i + 1, j, m, n); } if (j > 0 && heights[i][j - 1] >= heights[i][j]) { dfs(heights, flags, i, j - 1, m, n); } if (j < n - 1 && heights[i][j + 1] >= heights[i][j]) { dfs(heights, flags, i, j + 1, m, n); } } }
|