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:

  1. The order of returned grid coordinates does not matter.
  2. 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).

这道题给了我们一个二维数组,说是数组的左边和上边是太平洋,右边和下边是大西洋,假设水能从高处向低处流,问我们所有能流向两大洋的点的集合。刚开始博主没有理解题意,以为加括号的点是一条路径,连通两大洋的,但是看来看去感觉也不太对,后来终于明白了,是每一个点单独都有路径来通向两大洋。那么就是典型的搜索问题,我最开始想的是对于每个点都来搜索是否能到达边缘,只不过搜索的目标点不再是一个单点,而是所有的边缘点,照这种思路写出的代码无法通过 OJ 大数据集,那么就要想办法来优化代码,优化的方法跟之前那道 Surrounded Regions 很类似,都是换一个方向考虑问题,既然从每个点向中间扩散会 TLE,那么我们就把所有边缘点当作起点开始遍历搜索,然后标记能到达的点为 true,分别标记出 pacific 和 atlantic 能到达的点,那么最终能返回的点就是二者均为 true 的点。我们可以先用DFS来遍历二维数组,参见代码如下:

解法一:

class Solution {
public:
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
vector<pair<int, int>> res;
int m = matrix.size(), n = matrix[].size();
vector<vector<bool>> pacific(m, vector<bool>(n, false));
vector<vector<bool>> atlantic(m, vector<bool>(n, false));
for (int i = ; i < m; ++i) {
dfs(matrix, pacific, INT_MIN, i, );
dfs(matrix, atlantic, INT_MIN, i, n - );
}
for (int i = ; i < n; ++i) {
dfs(matrix, pacific, INT_MIN, , i);
dfs(matrix, atlantic, INT_MIN, m - , i);
}
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (pacific[i][j] && atlantic[i][j]) {
res.push_back({i, j});
}
}
}
return res;
}
void dfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, int pre, int i, int j) {
int m = matrix.size(), n = matrix[].size();
if (i < || i >= m || j < || j >= n || visited[i][j] || matrix[i][j] < pre) return;
visited[i][j] = true;
dfs(matrix, visited, matrix[i][j], i + , j);
dfs(matrix, visited, matrix[i][j], i - , j);
dfs(matrix, visited, matrix[i][j], i, j + );
dfs(matrix, visited, matrix[i][j], i, j - );
}
};

那么 BFS 的解法也可以做,用 queue 来辅助,开始把边上的点分别存入 queue 中,然后对应的 map 标记 true,然后开始 BFS 遍历,遍历结束后还是找 pacific 和 atlantic 均标记为 true 的点加入结果 res 中返回即可,参见代码如下:

解法二:

class Solution {
public:
vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[].empty()) return {};
vector<pair<int, int>> res;
int m = matrix.size(), n = matrix[].size();
queue<pair<int, int>> q1, q2;
vector<vector<bool>> pacific(m, vector<bool>(n, false)), atlantic = pacific;
for (int i = ; i < m; ++i) {
q1.push({i, });
q2.push({i, n - });
pacific[i][] = true;
atlantic[i][n - ] = true;
}
for (int i = ; i < n; ++i) {
q1.push({, i});
q2.push({m - , i});
pacific[][i] = true;
atlantic[m - ][i] = true;
}
bfs(matrix, pacific, q1);
bfs(matrix, atlantic, q2);
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (pacific[i][j] && atlantic[i][j]) {
res.push_back({i, j});
}
}
}
return res;
}
void bfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, queue<pair<int, int>>& q) {
int m = matrix.size(), n = matrix[].size();
vector<vector<int>> dirs{{,-},{-,},{,},{,}};
while (!q.empty()) {
auto t = q.front(); q.pop();
for (auto dir : dirs) {
int x = t.first + dir[], y = t.second + dir[];
if (x < || x >= m || y < || y >= n || visited[x][y] || matrix[x][y] < matrix[t.first][t.second]) continue;
visited[x][y] = true;
q.push({x, y});
}
}
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/417

参考资料:

https://leetcode.com/problems/pacific-atlantic-water-flow/

https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90733/java-bfs-dfs-from-ocean

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 417. Pacific Atlantic Water Flow 太平洋大西洋水流的更多相关文章

  1. 417 Pacific Atlantic Water Flow 太平洋大西洋水流

    详见:https://leetcode.com/problems/pacific-atlantic-water-flow/description/ C++: class Solution { publ ...

  2. [LeetCode] Pacific Atlantic Water Flow 太平洋大西洋水流

    Given an m x n matrix of non-negative integers representing the height of each unit cell in a contin ...

  3. LeetCode 417. Pacific Atlantic Water Flow

    原题链接在这里:https://leetcode.com/problems/pacific-atlantic-water-flow/description/ 题目: Given an m x n ma ...

  4. 【LeetCode】417. Pacific Atlantic Water Flow 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/pacific- ...

  5. 417. Pacific Atlantic Water Flow

    正常做的,用了645MS..感觉DFS的时候剪枝有问题.. 为了剪枝可能需要标记一个点的4种情况: 1:滨临大西洋,所有太平洋来的点可以通过: 2:濒临太平洋,所有大西洋来的点可以通过: 3:都不濒临 ...

  6. [Swift]LeetCode417. 太平洋大西洋水流问题 | Pacific Atlantic Water Flow

    Given an m x n matrix of non-negative integers representing the height of each unit cell in a contin ...

  7. Leetcode: Pacific Atlantic Water Flow

    Given an m x n matrix of non-negative integers representing the height of each unit cell in a contin ...

  8. [LeetCode] Pacific Atlantic Water Flow 题解

    题意 题目 思路 一开始想用双向广搜来做,找他们相碰的点,但是发现对其的理解还是不够完全,导致没写成功.不过,后来想清楚了,之前的错误可能在于从边界点进行BFS,其访问顺序应该是找到下一个比当前那个要 ...

  9. Java实现 LeetCode 417 太平洋大西洋水流问题

    417. 太平洋大西洋水流问题 给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度."太平洋"处于大陆的左边界和上边界,而"大西洋"处于大陆的 ...

随机推荐

  1. jQuery 遍历方法大全

    下表列出了用于jQuery 遍历所有方法. 方法 描述 add() 将元素添加到匹配的元素集中 addBack() 将上一组元素添加到当前组中 andSelf() 在版本1.8中已弃用. addBac ...

  2. iconfont采坑

    1. iconfont采坑 1.1. 前言 使用iconfont过程中踩过坑特此记录 不知道iconfont的这里也简单介绍一笔,阿里开放的一个图标素材库,用来快速找图标下载使用图标 iconfont ...

  3. RV32I基础整数指令集

    RV32I是32位基础整数指令集,它支持32位寻址空间,支持字节地址访问,仅支持小端格式(little-endian,高地址高位,低地址地位),寄存器也是32位整数寄存器.RV32I指令集的目的是尽量 ...

  4. boa移植 boa交叉编译

    官网:http://www.boa.org/ BOA 服务器是一个小巧高效的web服务器,是一个运行于unix或linux下的,支持CGI的.适合于嵌入式系统的单任务的http服务器,源代码开放.性能 ...

  5. Redis缓存和MySQL数据一致性方案(转)

    需求起因 在高并发的业务场景下,数据库大多数情况都是用户并发访问最薄弱的环节.所以,就需要使用redis做一个缓冲操作,让请求先访问到redis,而不是直接访问MySQL等数据库. 这个业务场景,主要 ...

  6. adb 连接夜神和逍遥模拟器

    然后运行cmd命令,cd到夜神安装目录,执行命令 adb connect 127.0.0.1:62001 nox_adb.exe connect 127.0.0.1:62001 逍遥模拟器 adb c ...

  7. 关与 @EnableConfigurationProperties 注解

    @EnableConfigurationProperties注解的作用是: 让使用 @ConfigurationProperties 注解的类生效. 当@EnableConfigurationProp ...

  8. c# 拉姆达表达式实现List去重

    c# 拉姆达表达式实现List去重 var list = studentlist.OrderByDescending(a => a.CreateDate).ToList(); Console.W ...

  9. vue 开发系列(十) VUE 作用域插槽

    使用场景 官方解释,有时让插槽内容能够访问子组件中才有的数据是很有用的.比如我们在使用ant-design-vue 的表格控件时. <a-table-column title="注释& ...

  10. Hibernate与Mybatis 对比

    见知乎:https://www.zhihu.com/question/21104468 总结: 1:业务简单,不涉及多表关联查询的,用Hibernate更快,但是当业务量上去后,需要精通Hiberna ...