417. Pacific Atlantic Water Flow
- Total Accepted: 5223
- Total Submissions: 16297
- Difficulty: Medium
- Contributors: Admin
Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
- The order of returned grid coordinates does not matter.
- Both m and n are less than 150.
-
Example:
Given the following 5x5 matrix: Pacific ~ ~ ~ ~ ~ ~ 1 2 2 3 (5) * ~ 3 2 3 (4) (4) * ~ 2 4 (5) 3 1 * ~ (6) (7) 1 4 5 * ~ (5) 1 1 2 4 * * * * * * Atlantic Return: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
解题思路:
可以看到要想流入Pacific则必须要流到第一行或者第一列的某一处,同理要想流入Atlantic则必须要流到最后一行或者最后一列的某一处,同时可流到Pacific和Atlantic的即为本题的解。本题可以从第一行的所有点和第一列的所有点进行dfs,找到所有能流到第一行或者第一列的点,同时从最后一行和最后一列进行dfs,找到所有能留到最后一行或者最后一列的点。最后即可得到答案。
代码展示:
class Solution {
public:
vector<vector<int> > tmp_mat;
vector<vector<int> > pvis;
vector<vector<int> > avis;
vector<pair<int,int>> ans;
void dfs(int i,int j,int who,int row,int col)
{
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
if(who==0)
{
pvis[i][j]=1;
for(int k=0;k<4;k++)
{
int curi=i+dir[k][0];
int curj=j+dir[k][1];
if(curi>=0&&curi<row&&curj>=0&&curj<col&&tmp_mat[curi][curj]>=tmp_mat[i][j]&&!pvis[curi][curj])
{
dfs(curi,curj,who,row,col);
}
}
}
else
{
avis[i][j]=1;
for(int k=0;k<4;k++)
{
int curi=i+dir[k][0];
int curj=j+dir[k][1];
if(curi>=0&&curi<row&&curj>=0&&curj<col&&tmp_mat[curi][curj]>=tmp_mat[i][j]&&!avis[curi][curj])
{
dfs(curi,curj,who,row,col);
}
}
}
}
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
int row=matrix.size();
tmp_mat= matrix;
if(!row) return ans;
int col=matrix[0].size();
vector<int> tmp(col,0);
for(int i=0;i<row;i++)
{
pvis.push_back(tmp);
avis.push_back(tmp);
}
for(int j=0;j<col;j++)
{
if(!pvis[0][j]) dfs(0,j,0,row,col);
}
for(int i=0;i<row;i++)
{
if(!pvis[i][0]) dfs(i,0,0,row,col);
}
for(int j=0;j<col;j++)
{
if(!avis[row-1][j]) dfs(row-1,j,1,row,col);
}
for(int i=0;i<row;i++)
{
if(!avis[i][col-1]) dfs(i,col-1,1,row,col);
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(avis[i][j]&&pvis[i][j])
{
ans.push_back(make_pair(i,j));
}
}
}
return ans;
}
};