思路
DFS,由边向高处找,找到最高处,就是答案点
代码实现(java)
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int m = heights.length;
int n = heights[0].length;
boolean canReachP[][] = new boolean[m][n],canReachX[][] = new boolean[m][n];
for(int i = 0; i < m; i++) {
dfs(heights, canReachP, i, 0);
dfs(heights, canReachX, i, n - 1);
}
for(int j = 0; j < n; j++) {
dfs(heights, canReachP, 0, j);
dfs(heights, canReachX, m - 1, j);
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(canReachP[i][j] && canReachX[i][j]) res.add(Arrays.asList(i, j));
}
}
return res;
}
public void dfs(int[][] heights, boolean[][] canReach, int i, int j) {
if(canReach[i][j]) return;
canReach[i][j] = true;
if(i - 1 >= 0 && heights[i-1][j] >= heights[i][j]) dfs(heights, canReach, i - 1, j);
if(j - 1 >= 0 && heights[i][j-1] >= heights[i][j]) dfs(heights, canReach, i, j - 1);
if(i + 1 < heights.length && heights[i+1][j] >= heights[i][j]) dfs(heights, canReach, i + 1, j);
if(j + 1 < heights[i].length && heights[i][j+1] >= heights[i][j]) dfs(heights, canReach, i, j + 1);
}
}
|