417. 太平洋大西洋水流问题(leetcode)
https://leetcode.cn/problems/pacific-atlantic-water-flow/description/
class Solution {
List<List<Integer>> res = new ArrayList<>();
int[] dx={0,1,0,-1};
int[] dy={1,0,-1,0};
int n;
int m;
int[][] heights;
boolean[][] vis;
boolean canWest;
boolean canEast;
public List<List<Integer>> pacificAtlantic(int[][] heights) {
// 思路:dfs搜索每个点是否能到太平和大西
m=heights.length;
n=heights[0].length;
this.heights=heights;
for(int i=0;i<heights.length;i++)
{
for(int j=0;j<heights[i].length;j++)
{
vis=new boolean[m][n];
canWest=false;
canEast=false;
dfs(i,j);
if(canEast && canWest)
{
res.add(List.of(i,j));
}
}
}
return res;
}
void dfs(int x,int y)
{
if(x==0 || y==0) canWest=true;
if(x==m-1 || y==n-1) canEast=true;
vis[x][y]=true;
for(int i=0;i<4;i++)
{
int a=dx[i]+x,b=dy[i]+y;
if(a>=0 && b>=0 && a<m && b<n && vis[a][b]==false && heights[x][y]>=heights[a][b])
{
dfs(a,b);
}
}
}
}