题目
给定一个 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]] (上图中带括号的单元).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pacific-atlantic-water-flow
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
如果对矩阵中每一个点进行搜索,并判断是否是合法的点,时间复杂度太高。所以逆向考虑,如果水从四周往高的地方流,那么能同时被太平洋和大西洋的水流到的点就是合法点。这样只需要搜索 2*(m+n) 次即可。
先搜太平洋再搜大西洋,在搜索过程中可以用数组记录一个点是否已经被流到过,最后得到两个矩阵,分别记录能被太平洋流到的点和能被大西洋流到的点,最后同时遍历两个数组得到答案。
C++ 代码
class Solution {
public:
const int direction[5] = {-1, 0, 1, 0, -1};
void DFS(vector<vector<int>>& heights, vector<vector<bool>>& connected, int m, int n, int old_x, int old_y) {
connected[old_x][old_y] = true;
for (int i = 0; i < 4; ++i) {
int x = old_x + direction[i];
int y = old_y + direction[i + 1];
if (x >= 0 && x < m && y >= 0 && y < n
&& !connected[x][y]
&& heights[x][y] >= heights[old_x][old_y]) {
DFS(heights, connected, m, n, x, y);
}
}
}
// for debugging
void displayVec(vector<vector<bool>>& vec) {
for (auto& item : vec) {
for (int num : item) {
cout << num << " ";
}
cout << endl;
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
vector<vector<int>> ans;
int m = heights.size();
if (m == 0)
return ans;
int n = heights[0].size();
if (n == 0)
return ans;
vector<vector<bool>> pacific_connected (m, vector<bool>(n, false));
vector<vector<bool>> atlantic_connected(m, vector<bool>(n, false));
for (int x = 0; x < m; ++x) {
if (!pacific_connected[x][0]) {
DFS(heights, pacific_connected, m, n, x, 0);
}
}
for (int y = 0; y < n; ++y) {
if (!pacific_connected[0][y]) {
DFS(heights, pacific_connected, m, n, 0, y);
}
}
for (int x = 0; x < m; ++x) {
if (!atlantic_connected[x][n - 1]) {
DFS(heights, atlantic_connected, m, n, x, n - 1);
}
}
for (int y = 0; y < n; ++y) {
if (!atlantic_connected[m - 1][y]) {
DFS(heights, atlantic_connected, m, n, m - 1, y);
}
}
// displayVec(pacific_connected);
// cout << endl;
// displayVec(atlantic_connected);
for (int x = 0; x < m; ++x) {
for (int y = 0; y < n; ++y) {
if (pacific_connected[x][y] && atlantic_connected[x][y]) {
ans.emplace_back(vector<int>{x, y});
}
}
}
return ans;
}
};