解题思路
题目需要找到既能流入太平洋同时也能流向大西洋的区域
初始想法是对每个区域进行dfs判断其能否到达两个大洋,但时间复杂度过高
因此更换一种思路,沿着边界进行dfs找到有多少区域能够流到边界位置,且需要两种边界的访问图,Pacific以及Atlantic,最后进行遍历,如果两个访问图都为true的位置,便是答案,即可以流向两个大洋
代码
class Solution {
List<List<Integer>> ans;
int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
public List<List<Integer>> pacificAtlantic(int[][] heights) {
ans = new ArrayList<>();
final int n = heights.length;
final int m = heights[0].length;
boolean[][] Pacific = new boolean[n][m];
boolean[][] Atlantic = new boolean[n][m];
//第一行和最后一行
for (int i = 0; i < m; i++) {
dfs(heights,0,i,n,m,Pacific);
dfs(heights,n-1,i,n,m,Atlantic);
}
//第一列和最后一列
for (int i = 0; i < n; i++) {
dfs(heights,i,0,n,m,Pacific);
dfs(heights,i,m-1,n,m,Atlantic);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (Pacific[i][j] && Atlantic[i][j]){
List<Integer> index = new ArrayList<>();
index.add(i);
index.add(j);
ans.add(index);
}
}
}
return ans;
}
private void dfs(int[][] heights, int x, int y,int n,int m,boolean[][] visited) {
visited[x][y] = true;
for (int[] next : dir) {
int nextX = x+next[0];
int nextY = y+next[1];
//相邻的的区域水位比此处高,继续进行搜索
if(nextX >= 0 && nextY >= 0 && nextX < n && nextY < m && !visited[nextX][nextY] && heights[x][y] <= heights[nextX][nextY]){
dfs(heights,nextX,nextY,n,m,visited);
}
}
}
}