作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: https://leetcode.com/problems/pacific-atlantic-water-flow/description/

题目描述

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:

Return:[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).

题目大意

上面一条边和左边一条边代表的是太平洋,右边一条边和下边一条边代表的是大西洋。

现在告诉你水往低处流,问哪些位置的水能同时流进太平洋和大西洋?

解题方法

要解决的问题:哪些位置的雨水能同时流进太平洋和大西洋。
重要思路:将水的流向反转,假设太平洋和大西洋的水 从低向高 “攀登”,分别能到达哪些位置,分别用 p_visiteda_visited 表示。两者的交集就代表能同时流向太平洋和大西洋的位置。



DFS

直接DFS求解。一般来说 DFS 需要有固定的起点,但是对于本题,4 条边都是能与大洋接壤的,那么就把 4条边界的每个位置都算作 DFS 的起点

使用两个二维数组 p_visiteda_visited,分别记录太平洋和大西洋的水能从低向高“攀登”到的位置。

然后对 4 条边进行遍历,看以这些边的每个位置为起点,进行攀登;把能到达的哪些的位置,分别在 p_visiteda_visited标记出来。

注意了,因为是从边界向中间去“攀登”,所以,这个时候是新的点要比当前的点海拔高才行。

Python代码如下:

class Solution(object):def pacificAtlantic(self, matrix):""":type matrix: List[List[int]]:rtype: List[List[int]]"""if not matrix or not matrix[0]: return []m, n = len(matrix), len(matrix[0])p_visited = [[False] * n for _ in range(m)]a_visited = [[False] * n for _ in range(m)]for i in range(m):self.dfs(p_visited, matrix, m, n, i, 0)self.dfs(a_visited, matrix, m, n, i, n -1)for j in range(n):self.dfs(p_visited, matrix, m, n, 0, j)self.dfs(a_visited, matrix, m, n, m - 1, j)res = []for i in range(m):for j in range(n):if p_visited[i][j] and a_visited[i][j]:res.append([i, j])return resdef dfs(self, visited, matrix, m, n, i, j):visited[i][j] = Truedirections = [(-1, 0), (1, 0), (0, 1), (0, -1)]for dire in directions:x, y = i + dire[0], j + dire[1]if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or matrix[x][y] < matrix[i][j]:continueself.dfs(visited, matrix, m, n, x, y)

C++代码如下:

class Solution {public:vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {if (matrix.empty() || matrix[0].empty()) return {};const int M = matrix.size();const int N = matrix[0].size();vector<vector<bool>> p_visited(M, vector<bool>(N));vector<vector<bool>> a_visited(M, vector<bool>(N));for (int i = 0; i < M; ++i) {dfs(matrix, p_visited, i, 0);dfs(matrix, a_visited, i, N - 1);}for (int j = 0; j < N; ++j) {dfs(matrix, p_visited, 0, j);dfs(matrix, a_visited, M - 1, j);}vector<pair<int, int>> res;for (int i = 0; i < M; ++i) {for (int j = 0; j < N; ++j) {if (p_visited[i][j] && a_visited[i][j]) {res.push_back({i, j});}}}return res;}void dfs(vector<vector<int>>& matrix, vector<vector<bool>>& visited, int i, int j) {const int M = matrix.size();const int N = matrix[0].size();visited[i][j] = true;vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};for (auto d : dirs) {int nx = i + d.first;int ny = j + d.second;if (nx >= 0 && nx < M && ny >= 0 && ny < N && !visited[nx][ny] && matrix[nx][ny] >= matrix[i][j]) {dfs(matrix, visited, nx, ny);}}}
};

最坏情况下的时间复杂度:O((M+N)∗MN)O((M+N)*MN)O((M+N)∗MN)
空间复杂度: O(MN)O(MN)O(MN)。

参考资料:

https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90739/Python-DFS-bests-85.-Tips-for-all-DFS-in-matrix-question./181815

总结

  1. DFS 的变化。

日期

2018 年 10 月 1 日 —— 欢度国庆!

【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. Pacific Atlantic Water Flow 太平洋大西洋水流问题

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

  3. leetcode 417. Pacific Atlantic Water Flow | 417. 太平洋大西洋水流问题(DFS,经典“感染”思路)

    题目 https://leetcode.com/problems/pacific-atlantic-water-flow/ 题解 一开始的错误思路:(区分"主动"与"被动 ...

  4. LeetCode Pacific Atlantic Water Flow(flood fill)

    问题:给出一个二维数组,数组中的元素非负.左边和上边表示大平洋,右边和下边表示大西洋.水可以向上下左右四个方向流动,但是要求不高于它.要求输出可以到达两大洋的坐标 思路:因为从高到不高于当前位置的位置 ...

  5. ​LeetCode刷题实战417:太平洋大西洋水流问题

    算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试.所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 ! 今天和大家 ...

  6. LeetCode 417.太平洋大西洋水流问题

    LeetCode 417.太平洋大西洋水流问题 有一个 m × n 的长方形岛屿,与 太平洋 和 大西洋 相邻. "太平洋" 处于大陆的左边界和上边界,而 "大西洋&qu ...

  7. Leetcode 417 题 太平洋大西洋水流问题

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

  8. 417. 太平洋大西洋水流问题(medium) -力扣(leetCode)逆流而上,JS图的深度优先遍历算法

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

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

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

最新文章

  1. 三年后75%企业数据将移至云端?SAP新应用加速云服务
  2. RUBY,玩玩~~~
  3. Spring-AOP 引介切面
  4. ApartmentState.STA
  5. C/C++心得-结构体
  6. python产生随机数random.random_Python内置random模块生成随机数的方法
  7. python 客户端_Python一个简单的通信程序(客户端 服务器)
  8. 允许Fedora 12以root身份登录图形界面
  9. 如何在Dev-Cpp中使用C++11中的函数:stoi、to_string、unordered_map、unordered_set、auto
  10. 第2节 mapreduce深入学习:15、reduce端的join算法的实现
  11. 安卓绿色联盟安全标准1.0到2.0,让用户隐私更安全
  12. 第一个scrum会议
  13. 1、试卷名称2013年下半年系统集成项目管理工程师真题
  14. 0068 terra vista 4.0安装包及破解教程
  15. 【Apache+Tomcat+Session+Memcache 高性能群集搭建】
  16. 快速将视频分解成一帧帧的图片
  17. 让手机桌面显示计算机,被忽略的Win10新功能,让手机屏幕轻松显示在电脑屏幕上?...
  18. 鼠鼠百科--数据恢复
  19. 你的金钱和时间流向哪,你的人生就什么样!
  20. oracle查询遇到关键字

热门文章

  1. android访问SD卡的权限
  2. 上线一月破千万,孙俪都是其粉丝,揭秘花粉儿APP的成长秘诀
  3. How To Download Youtube Videos Without any software
  4. 全志linux关机键,全志平台linux启动流程分析
  5. 获取本月,上月,下月 第一天和最后一天 java
  6. 孙正义的12条成功之道
  7. javascript学习(1)随机点名应用
  8. 完美的扎克伯格,倒霉的Facebook
  9. 看新闻的时候,你们手机都用什么软件?
  10. Python罕见的但是却常用的内置函数