题目描述:
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).
矩阵的左边界和上边界是太平洋,右边就和下边界是大西洋,矩阵中每个元素的值代表坐标对应的高度,求哪些坐标的的水可以同时流到太平洋和大西洋。可以从矩阵的边界出发,利用递归搜索可以遍历到的所有节点,就代表哪些坐标的水可以流到太平洋或大西洋。
class Solution {
public:
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<pair<int,int>> result;
if(matrix.size()==0||matrix[0].size()==0) return result;
int m=matrix.size();
int n=matrix[0].size();
vector<vector<bool>> P(m,vector<bool>(n,false));
vector<vector<bool>> A(m,vector<bool>(n,false));
for(int i=0;i<m;i++)
{
search_surround(i,0,P,matrix);
search_surround(i,n-1,A,matrix);
}
for(int j=0;j<n;j++)
{
search_surround(0,j,P,matrix);
search_surround(m-1,j,A,matrix);
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if(P[i][j]==true&&A[i][j]==true)
result.push_back(pair<int,int>(i,j));
return result;
}
void search_surround(int i, int j, vector<vector<bool>>& X, vector<vector<int>> matrix)
{
if(X[i][j]==true) return;
X[i][j]=true;
if(i-1>=0&&matrix[i][j]<=matrix[i-1][j]) search_surround(i-1,j,X,matrix);
if(i+1<X.size()&&matrix[i][j]<=matrix[i+1][j]) search_surround(i+1,j,X,matrix);
if(j-1>=0&&matrix[i][j]<=matrix[i][j-1])search_surround(i,j-1,X,matrix);
if(j+1<X[0].size()&&matrix[i][j]<=matrix[i][j+1])search_surround(i,j+1,X,matrix);
}
};