class Solution {
static int[][] dir={{1,0},{-1,0},{0,1},{0,-1}};
static int[][] heights;
static int m,n;
public List<List<Integer>> pacificAtlantic(int[][] param) {
heights=param;
m=heights.length;
n=heights[0].length;
boolean[][] tpy=new boolean[m][n];
boolean[][] dxy=new boolean[m][n];
// 第一列,第一行~最后行
for(int i=0;i<m;i++){
dfs(i,0,tpy);
}
// 第一行,第二列~最后列
for(int i=1;i<n;i++){
dfs(0,i,tpy);
}
// 第一行~最后行,最后列
for(int i=0;i<m;i++){
dfs(i,n-1,dxy);
}
// 最后行,第一列~倒数第二列
for(int i=0;i<n-1;i++){
dfs(m-1,i,dxy);
}
List<List<Integer>> ans=new ArrayList<>();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(tpy[i][j]&&dxy[i][j]){
List<Integer> cell=new ArrayList<>();
cell.add(i);
cell.add(j);
ans.add(cell);
}
}
}
return ans;
}
private void dfs(int r,int c,boolean[][] ocean){
if(ocean[r][c]){
return;
}
ocean[r][c]=true;
for(int[] tmp:dir){
int newR=r+tmp[0];
int newC=c+tmp[1];
if(newR>=0&&newR<m&&newC>=0&&newC<n&&heights[newR][newC]>=heights[r][c]){
dfs(newR,newC,ocean);
}
}
}
}