class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
int m = heights.size();
int n = heights[0].size();
vector<vector<bool>> POcean(m, vector<bool>(n, false));
vector<vector<bool>> AOcean(m, vector<bool>(n, false));
// 从左右两列遍历
for (int i = 0; i < m; ++i)
{
dfs(heights, POcean, i, 0);
dfs(heights, AOcean, i, n - 1);
}
//从上下两行遍历
for (int i = 0; i < n; ++i)
{
dfs(heights, POcean, 0, i);
dfs(heights, AOcean, m - 1, i);
}
// 两层遍历
vector<vector<int>> result;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (POcean[i][j] && AOcean[i][j])
result.push_back({i, j});
}
}
return result;
}
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
void dfs(vector<vector<int>>& heights, vector<vector<bool>>& visited, int row, int col)
{
if (visited[row][col]) return;
visited[row][col] = true;
for (int i = 0; i < 4; ++i)
{
int newrow = row + dir[i][0];
int newcol = col + dir[i][1];
if (newrow < 0 || newrow >= heights.size() || newcol < 0 || newcol >= heights[0].size()) continue;
if (heights[newrow][newcol] < heights[row][col]) continue;
dfs(heights, visited, newrow, newcol);
}
}
};