Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pacific-atlantic-water-flow.py 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-12 01:33 +08:00 . remove sensitive question description
# Time: O(m * n)
# Space: O(m * n)
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
PACIFIC, ATLANTIC = 1, 2
def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res):
if (not 0 <= x < len(matrix)) or \
(not 0 <= y < len(matrix[0])) or \
matrix[x][y] < prev_height or \
(visited[x][y] | prev_val) == visited[x][y]:
return
visited[x][y] |= prev_val
if visited[x][y] == (PACIFIC | ATLANTIC):
res.append((x, y))
for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res)
if not matrix:
return []
res = []
m, n = len(matrix),len(matrix[0])
visited = [[0 for _ in xrange(n)] for _ in xrange(m)]
for i in xrange(m):
pacificAtlanticHelper(matrix, i, 0, float("-inf"), PACIFIC, visited, res)
pacificAtlanticHelper(matrix, i, n - 1, float("-inf"), ATLANTIC, visited, res)
for j in xrange(n):
pacificAtlanticHelper(matrix, 0, j, float("-inf"), PACIFIC, visited, res)
pacificAtlanticHelper(matrix, m - 1, j, float("-inf"), ATLANTIC, visited, res)
return res
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助