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又能与Altantic相连的点,这样问题一分为二,我们先记录那些点是与Pacific相连的点,再记录与Altantic相连的点,最后遍历即可。
Code
class Solution {
public:
int row;
int col;
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<pair<int, int>> res;
row = matrix.size();
if (row == 0)
return res;
col = matrix[0].size();
for (int i = 0; i < row; i ++)
{
matrix[i].insert(matrix[i].begin(), INT_MIN);
matrix[i].push_back(INT_MIN);
}
matrix.insert(matrix.begin(), vector<int>(col+2, INT_MIN));
matrix.push_back(vector<int>(col+2, INT_MIN));
vector<vector<int>> toPacific(row+2, vector<int>(col+2, 0));
vector<vector<int>> toAtlantic(row+2, vector<int>(col+2, 0));
for (int i = 1; i <= row; i ++)
{
getOcean(matrix, i, 1, toPacific);
getOcean(matrix, i, col, toAtlantic);
}
for (int i = 1; i <= col; i ++)
{
getOcean(matrix, 1, i, toPacific);
getOcean(matrix, row, i, toAtlantic);
}
for (int i = 1; i <= row; i ++)
for (int j = 1; j <= col; j ++)
{
if (toPacific[i][j] == 1 && toAtlantic[i][j] == 1)
res.push_back(make_pair(i-1, j-1));
}
return res;
}
void getOcean(vector<vector<int>>& matrix, int x, int y, vector<vector<int>>& toOcean)
{
if (toOcean[x][y] == 1)
return;
if (x <= 0 || y <= 0 || x > row || y > col)
return;
toOcean[x][y] = 1;
int h = matrix[x][y];
if (matrix[x-1][y] >= h)
getOcean(matrix, x-1, y, toOcean);
if (matrix[x+1][y] >= h)
getOcean(matrix, x+1, y, toOcean);
if (matrix[x][y-1] >= h)
getOcean(matrix, x, y-1, toOcean);
if (matrix[x][y+1] >= h)
getOcean(matrix, x, y+1, toOcean);
return;
}
};
运行效率
Runtime: 48 ms, faster than 97.55% of C++ online submissions for Pacific Atlantic Water Flow.
Memory Usage: 17.1 MB, less than 27.69% of C++ online submissions for Pacific Atlantic Water Flow.