原题链接:417. 太平洋大西洋水流问题
solution:
本题采用逆向思考,考虑太平洋和大西洋出发能抵达的点,从太平洋出发能抵达的点或1,从大西洋出发能抵达的点或2,因此两个都可以抵达的点值就为3.
dfs做法:
class Solution {
public:
vector<vector<int>> w; //保存岛屿
vector<vector<int>> sta; //保存每个点的状态
vector<vector<int>> res; //定义返回值
int dx[4] = {-1,0,1,0},dy[4] = {0,-1,0,1};
void dfs(int x,int y,int state) {
if(sta[x][y] & state) return; //sta[x][y] & sta = true表示已经遍历过了
//没有遍历过则
sta[x][y] |= state;
for(int i = 0;i < 4;i++){
int x1 = x + dx[i];
int y1 = y + dy[i];
if(x1 >= 0 && x1 < w.size() && y1 >= 0 && y1 < w[0].size() && w[x1][y1] >= w[x][y]){
dfs(x1,y1,state);
}
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
w = heights;
if(w.empty() || w[0].empty()) return res;
int m = heights.size();
int n = heights[0].size();
sta.resize(m, vector<int> (n));
for(int i = 0;i < n;i++) dfs(0,i,1);
for(int i = 0;i < m;i++) dfs(i,0,1); //太平洋出发,第0为或1
for(int j = 0;j < n;j++) dfs(m - 1,j,2);
for(int j = 0;j < m;j++) dfs(j,n - 1,2); //大西洋出发,第1位或1
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++){
if(sta[i][j] == 3) res.push_back({i,j});
}
return res;
}
};
bfs做法:
class Solution {
public:
int m,n;
vector<vector<int>> w; //保存岛屿
vector<vector<int>> sta; //保存岛屿遍历的状态
vector<vector<int>> res; //定义返回值
typedef pair<int,int> PII;
int dx[4] = {-1,0,1,0},dy[4] = {0,-1,0,1};
queue<PII> q; //定义队列保存要遍历的点
void bfs(int state) {
while(!q.empty()){
auto t = q.front();
q.pop();
int x = t.first,y = t.second;
if(sta[x][y] & state) continue; //已经遍历过了
sta[x][y] |= state;
for(int i = 0;i < 4;i++){
int x1 = x + dx[i];
int y1 = y + dy[i];
if(x1 >= 0 && x1 < m && y1 >= 0 && y1 < n && w[x1][y1] >= w[x][y]){
q.push({x1,y1});
}
}
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
w = heights;
if(w.empty() || w[0].empty()) return res;
m = w.size();
n = w[0].size();
sta.resize(m, vector<int> (n));
for(int i = 0;i < m;i++) q.push({i,0});
for(int j = 0;j < n;j++) q.push({0,j});
bfs(1); //太平洋
for(int i = 0;i < m;i++) q.push({i,n - 1});
for(int j = 0;j < n;j++) q.push({m - 1,j});
bfs(2); //大西洋
for(int i = 0;i < m;i++)
for(int j = 0;j < n;j++){
if(sta[i][j] == 3) res.push_back({i,j});
}
return res;
}
};