【LeetCode】417. Pacific Atlantic Water Flow 解题报告(Python & C++)
作者: 负雪明烛
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:
- 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求解。一般来说DFS需要有固定的起点,但是对于这个题,四条边界的每个位置都算作起点。
使用两个二维数组,分别记录每个位置的点能不能到达太平洋和大西洋。然后对4条边界进行遍历,看这些以这些边为起点能不能所有的地方。注意了,因为是从边界向中间去寻找,所以,这个时候是新的点要比当前的点海拔高才行。
最坏情况下的时间复杂度是O((M+N)*MN),空间复杂度是O(MN)。
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 res
def dfs(self, visited, matrix, m, n, i, j):
visited[i][j] = True
directions = [(-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]:
continue
self.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);
}
}
}
};
参考资料:
日期
2018 年 10 月 1 日 —— 欢度国庆!
【LeetCode】417. Pacific Atlantic Water Flow 解题报告(Python & C++)的更多相关文章
- [LeetCode] 417. Pacific Atlantic Water Flow 太平洋大西洋水流
Given an m x n matrix of non-negative integers representing the height of each unit cell in a contin ...
- LeetCode 417. Pacific Atlantic Water Flow
原题链接在这里:https://leetcode.com/problems/pacific-atlantic-water-flow/description/ 题目: Given an m x n ma ...
- 417 Pacific Atlantic Water Flow 太平洋大西洋水流
详见:https://leetcode.com/problems/pacific-atlantic-water-flow/description/ C++: class Solution { publ ...
- 417. Pacific Atlantic Water Flow
正常做的,用了645MS..感觉DFS的时候剪枝有问题.. 为了剪枝可能需要标记一个点的4种情况: 1:滨临大西洋,所有太平洋来的点可以通过: 2:濒临太平洋,所有大西洋来的点可以通过: 3:都不濒临 ...
- [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 ...
- 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 ...
- [LeetCode] Pacific Atlantic Water Flow 题解
题意 题目 思路 一开始想用双向广搜来做,找他们相碰的点,但是发现对其的理解还是不够完全,导致没写成功.不过,后来想清楚了,之前的错误可能在于从边界点进行BFS,其访问顺序应该是找到下一个比当前那个要 ...
- [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 ...
- 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...
随机推荐
- mysql-彻底删除方法
一.如果是使用yum安装的mysql,使用如下命令进行卸载(不能确定使用何种方式安装的mysql情况下,按后续步骤一一进行处理即可): yum remove mysql mysql-server my ...
- Mysql-单个left join 计算逻辑(一对多问题)
BUG背景: 我们有一个订单表 和 一个 物流表 它们通过 订单ID 进行一对一的关系绑定.但是由于物流表在保存订单信息的时候没有做判断该订单是否已经有物流信息,这就变成同一个订单id在物流表中存在多 ...
- [源码解析] PyTorch 分布式 Autograd (6) ---- 引擎(下)
[源码解析] PyTtorch 分布式 Autograd (6) ---- 引擎(下) 目录 [源码解析] PyTtorch 分布式 Autograd (6) ---- 引擎(下) 0x00 摘要 0 ...
- 前端4 — jQuery — 更新完毕
1.下载jQuery 网址:Download jQuery | jQuery 最好下载最新版的,因为有什么bug问题,最新版的都会有,所以学技术就用最新版的,实际开发用的时候就要讲究了 2.开始用j ...
- linux 实用指令文件目录类
目录 linux实用指令文件目录类 路径 pwd指令 cd指令 操作文件夹/文件 ls指令 mkdir rmdir touch cp(重要) rm mv 操作内容 cat more less > ...
- Hadoop入门 完全分布式运行模式-集群配置
目录 集群配置 集群部署规划 配置文件说明 配置集群 群起集群 1 配置workers 2 启动集群 总结 3 集群基本测试 上传文件到集群 查看数据真实存储路径 下载 执行wordcount程序 配 ...
- Scala(四)【集合基础入门】
目录 一.Array 二. List 三.Set 四.Tuple 五.Map 一.Array package com.bigdata.scala.day01 /** * @description: 不 ...
- c#中实现串口通信的几种方法
c#中实现串口通信的几种方法 通常,在C#中实现串口通信,我们有四种方法: 第一:通过MSCOMM控件这是最简单的,最方便的方法.可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册 ...
- mysql 5.7 压缩包安装教程
前言 : 避免之前装的MySQL影响 首先进入dos窗口执行 sc delete mysql 删除已有的mysql服务 (一) 下载MySQL5.7 版本压缩包 网址 https://de ...
- 【编程思想】【设计模式】【基础模式Fundamental】delegation_pattern
Python版 https://github.com/faif/python-patterns/blob/master/fundamental/delegation_pattern.py #!/usr ...