要求:水往低处流向两边,找同时能留到左边或者上边、右边或者下边的
思路:
法一:对每个点暴力dfs,640ms勉强过了hh
class Solution {
public:
void dfs(vector<vector<int>>& heights,int i,int j,bool &topa,bool &toat,map<pair<int,int>,int> &visited){
if(i==0||j==0)topa=true;
if(i+1==heights.size()||j+1==heights[0].size())toat=true;
if(topa&&toat)return;
visited[make_pair(i,j)]=1;
int di[4]={0,0,1,-1};
int dj[4]={1,-1,0,0};
for(int k=0;k<4;++k){
if(i+di[k]<0||i+di[k]>=heights.size()||j+dj[k]<0||j+dj[k]>=heights[0].size())continue;
if(heights[i+di[k]][j+dj[k]]<=heights[i][j]&&visited.count(make_pair(i+di[k],j+dj[k]))==0)
dfs(heights,i+di[k],j+dj[k],topa,toat,visited);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
vector<vector<int>> ans;
for(int i=0;i<heights.size();++i){
for(int j=0;j<heights[0].size();++j){
bool topa=false,toat=false;
map<pair<int,int>,int> visited;
dfs(heights,i,j,topa,toat,visited);
if(topa&&toat)ans.push_back({i,j});
}
}
return ans;
}
};
法二:直接从边界找能到达的点,112ms
class Solution {
public:
void dfs(vector<vector<int>>& heights,int i,int j,map<pair<int,int>,int> &visited){
visited[make_pair(i,j)]=1;
int di[4]={0,0,1,-1};
int dj[4]={1,-1,0,0};
for(int k=0;k<4;++k){
if(i+di[k]<0||i+di[k]>=heights.size()||j+dj[k]<0||j+dj[k]>=heights[0].size())continue;
if(heights[i+di[k]][j+dj[k]]>=heights[i][j]&&visited.count(make_pair(i+di[k],j+dj[k]))==0)
dfs(heights,i+di[k],j+dj[k],visited);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
vector<vector<int>> ans;
map<pair<int,int>,int> visited1;
for(int j=0,i=0;j<heights[0].size();++j)
dfs(heights,i,j,visited1);
for(int j=0,i=0;i<heights.size();++i)
dfs(heights,i,j,visited1);
map<pair<int,int>,int> visited2;
for(int j=0,i=(int)heights.size()-1;j<heights[0].size();++j)
dfs(heights,i,j,visited2);
for(int j=(int)heights[0].size()-1,i=0;i<heights.size();++i)
dfs(heights,i,j,visited2);
for(auto &m1:visited1)
for(auto &m2:visited2)
if(m1.first==m2.first)ans.push_back({m1.first.first,m1.first.second});
return ans;
}
};