题目描述
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).
思路
DFS和BFS貌似都可以。
只写了BFS。满足条件的时候扩展。
代码
class Solution {
public:
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
n = matrix.size();
m = matrix[0].size();
dp1 = vector<vector<int>> (n, vector<int>(m, 0));
dp2 = vector<vector<int>> (n, vector<int>(m, 0));
queue<pair<int, int>> que1;
for (int i=0; i<n; ++i) {
dp1[i][0] = 1;
que1.push({i, 0});
}
for (int i=0; i<m; ++i) {
dp1[0][i] = 1;
que1.push({0, i});
}
bfs(que1, dp1, matrix);
queue<pair<int, int>> que2;
for (int i=0; i<n; ++i) {
dp2[i][m-1] = 1;
que2.push({i, m-1});
}
for (int i=0; i<m; ++i) {
dp2[n-1][i] = 1;
que2.push({n-1, i});
}
bfs(que2, dp2, matrix);
vector<vector<int>> res;
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
if (dp1[i][j] && dp2[i][j]) {
res.push_back({i, j});
}
}
}
return res;
}
private:
vector<vector<int>> dp1;
vector<vector<int>> dp2;
vector<int> dir {1, 0, -1, 0, 1};
int n, m;
void bfs(queue<pair<int, int>>& que, vector<vector<int>>& dp, vector<vector<int>>& matrix) {
while(!que.empty()) {
int x = que.front().first;
int y = que.front().second;
que.pop();
for (int i=0; i<4; ++i) {
int nx = x + dir[i];
int ny = y + dir[i+1];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
if (dp[nx][ny]) continue;
if (matrix[nx][ny] < matrix[x][y]) continue;
dp[nx][ny] = 1;
que.push({nx, ny});
}
}
}
};

本文介绍了一种使用BFS算法解决的问题,即在一个由非负整数构成的矩阵中找到那些能够流向太平洋和大西洋的网格坐标。通过从边缘开始进行广度优先搜索,我们可以在不超过150x150的矩阵中找出所有符合条件的位置。
511





