给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
提示:
输出坐标的顺序不重要
m 和 n 都小于150
示例:
给定下面的 5x5 矩阵:
太平洋 ~ ~ ~ ~ ~
~ 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 *
* * * * * 大西洋
返回:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
class Solution {
public:
vector<bool> dfs1(vector<vector<int> >& matrix,vector<vector<int> >&sign,vector<vector<vector<int>> >&sig,vector<bool>& num,int i,int j,int ROM,int COL){
sign[i][j] = ;
if(i == || j == ){num[] = true;}
if(i == ROM - || j == COL - ){num[] = true;}
if(sig[i][j][] != -&&sig[i][j][]!= -){
if(sig[i][j][] == ){num[] = true;}
if(sig[i][j][] == ){num[] = true;}
return num;
}
if(num[]&&num[]){return num;}
int value = matrix[i][j];
if(i != ){
if(value >= matrix[i - ][j]&&!sign[i - ][j]){
num = dfs1(matrix,sign,sig,num,i-,j,ROM,COL);
}
}
if(j != ){
if(value >= matrix[i][j - ]&&!sign[i][j - ]){
num = dfs1(matrix,sign,sig,num,i,j - ,ROM,COL);
}
}
if(i != ROM - ){
if(value >= matrix[i + ][j]&&!sign[i + ][j]){
num = dfs1(matrix,sign,sig,num,i + ,j,ROM,COL);
}
}
if(j != COL - ){
if(value >= matrix[i][j+]&&sign[i][j+] == ){
num = dfs1(matrix,sign,sig,num,i,j+,ROM,COL);
}
}
return num;
}
vector<vector<int> > pacificAtlantic(vector<vector<int> >& matrix) {
if(matrix.empty()){return matrix;}
int COL = matrix[].size();
int ROM = matrix.size();
vector<vector<int> >result;
vector<vector<int> >sign1(ROM,vector<int>(COL,));
vector<vector<int> >sign;
vector<vector<vector<int> > >sig(ROM,vector<vector<int> >(COL,vector<int>(,-)));
vector<bool> zz(,false);
for(int i = ROM - ;i >= ;i--){
for(int j = ;j < COL;j++){
sign =sign1;
zz = dfs1(matrix,sign,sig,zz,i,j,ROM,COL);
if(zz[]){
sig[i][j][] = ;
if(zz[]){
sig[i][j][] = ;
result.push_back({i,j});
}
else{sig[i][j][] = ;}
}
else{
sig[i][j][] = ;
if(zz[]){
sig[i][j][] = ;
}
else{
sig[i][j][] = ;
}
}
zz[] = false;zz[] = false;
}
}
return result;
}
};