解题思路:
这是一道经典DFS变形问题,需要两遍DFS,第一遍是为了找到通往大西洋的雨水连通图,第二遍是寻找通往太平洋的雨水连通图,最后对比两个连通图的连通状态,把都连通的点找出,代码如下:
class Solution {
private:
int m, n;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
vector<vector<int>> ans;
m = heights.size(), n = heights[0].size();
vector<vector<bool>> visitPacific(m, vector<bool>(n, false));
vector<vector<bool>> visitAtlantic(m, vector<bool>(n, false));
// 遍历左界和右界
for(int i = 0; i < m; i ++) {
dfs(heights, visitPacific, i, 0);
dfs(heights, visitAtlantic, i, n - 1);
}
// 遍历上界和下界
for(int j = 0; j < n; j ++) {
dfs(heights, visitPacific, 0, j);
dfs(heights, visitAtlantic, m - 1, j);
}
for(int i = 0; i < m; i ++) {
for(int j = 0; j < n; j ++) {
if(visitAtlantic[i][j] && visitPacific[i][j]) {
ans.push_back({i, j});
}
}
}
return ans;
}
void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int x, int y) {
visited[x][y] = true;
for(int i = 0 ; i < 4; i ++) {
int nextx = x + dir[i][0];
int nexty = y + dir[i][1];
// 不越界且未访问过
if(nextx >= 0 && nextx < m && nexty >= 0 && nexty < n && !visited[nextx][nexty]) {
// 满足水流条件
if(heights[nextx][nexty] >= heights[x][y]) {
dfs(heights, visited, nextx, nexty);
}
}
}
return;
}
};