题目描述:
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 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).
题目大意:
给定一个m x n
的非负整数矩阵,表示一块大陆的每个单元格高度,“太平洋”在矩阵的左边和上边,“大西洋”在矩阵的右边和下边。
水只向四个方向流动(上,下,左,右),从一个单元格流向另一个等高或者更低的单元格。
寻找格子坐标中水既可以流向太平洋,又可以流向大西洋的点集。
注意:
返回坐标的顺序不重要
m和n均小于150
解题思路:
BFS(广度优先搜索)
将矩形的左边和上边各点加入“太平洋”点集pacific
将矩形的右边和下边各点加入“大西洋”点集atlantic
分别对pacific与atlantic执行BFS
两者的交集即为答案。
Python代码:
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
m = len(matrix)
n = len(matrix[0]) if m else 0
if m * n == 0: return []
topEdge = [(0, y) for y in range(n)]
leftEdge = [(x, 0) for x in range(m)]
pacific = set(topEdge + leftEdge)
bottomEdge = [(m - 1, y) for y in range(n)]
rightEdge = [(x, n - 1) for x in range(m)]
atlantic = set(bottomEdge + rightEdge)
def bfs(vset):
dz = zip((1, 0, -1, 0), (0, 1, 0, -1))
queue = list(vset)
while queue:
hx, hy = queue.pop(0)
for dx, dy in dz:
nx, ny = hx + dx, hy + dy
if 0 <= nx < m and 0 <= ny < n:
if matrix[nx][ny] >= matrix[hx][hy]:
if (nx, ny) not in vset:
queue.append((nx, ny))
vset.add((nx, ny))
bfs(pacific)
bfs(atlantic)
result = pacific & atlantic
return map(list, result)
本文链接:http://bookshadow.com/weblog/2016/10/09/leetcode-pacific-atlantic-water-flow/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。