class Solution {
public List<List<Integer>> pacificAtlantic(int[][] heights) {
int lengthX=heights.length;
int lengthY=heights[0].length;
List<List<Integer>> result=new ArrayList<>();
boolean[][] canReachPacific=new boolean[lengthX][lengthY];
boolean[][] canReachAtlantic=new boolean[lengthX][lengthY];
for(int i=0;i<lengthX;i++){
dfs(heights,i,0,canReachPacific);
dfs(heights,i,lengthY-1,canReachAtlantic);
}
for(int j=0;j<lengthY;j++){
dfs(heights, 0, j, canReachPacific);
dfs(heights, lengthX-1 , j, canReachAtlantic);
}
for(int i=0;i<lengthX;i++){
for(int j=0;j<lengthY;j++){
if(canReachPacific[i][j] && canReachAtlantic[i][j]){
result.add(Arrays.asList(i,j));
}
}
}
return result;
}
public void dfs(int[][] heights, int i, int j , boolean[][] canReach){
int lengthX=heights.length;
int lengthY=heights[0].length;
int[][] directions={{1,0},{0,-1},{-1,0},{0,1}};
if( canReach[i][j]){
return;
}
canReach[i][j]=true;
for(int[] direction:directions){
int a = i+direction[0];
int b = j+direction[1];
if(0<=a && a<lengthX && 0<=b && b<lengthY && heights[i][j] <= heights[a][b] ){
dfs(heights,a,b,canReach);
}
}
}
}
09-10
09-10