417. 太平洋大西洋水流问题
代码使用队列进行广度搜索,分别遍历太平洋 和大西洋的河流,取交集。
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
set<pair<int,int>> pacSet;
set<pair<int,int>> atlSet;
vector<vector<int>> ans;
queue<pair<int,int>> que;
int m = heights.size();
int n = heights[0].size();
for(int i=0;i<n;++i)
{
que.push({0,i});
pacSet.insert({0,i});
}
for(int i=1;i<m;++i)
{
que.push({i,0});
pacSet.insert({i,0});
}
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
while(!que.empty())
{
auto t = que.front();
que.pop();
int x = t.first;
int y = t.second;
for(int i=0;i<4;++i)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0 && nx<m && ny>=0 && ny <n && !pacSet.count({nx,ny}) && heights[nx][ny] >= heights[x][y])
{
que.push({nx,ny});
pacSet.insert({nx,ny});
}
}
}
for(int i=0;i<n;++i)
{
que.push({m-1,i});
atlSet.insert({m-1,i});
}
for(int i=0;i<m-1;++i)
{
que.push({i,n-1});
atlSet.insert({i,n-1});
}
while(!que.empty())
{
auto t = que.front();
que.pop();
int x = t.first;
int y = t.second;
if(pacSet.count({x,y}))
{
ans.push_back({x,y});
}
for(int i=0;i<4;++i)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0 && nx<m && ny>=0 && ny <n && !atlSet.count({nx,ny}) && heights[nx][ny] >= heights[x][y])
{
que.push({nx,ny});
atlSet.insert({nx,ny});
}
}
}
return ans;
}
};