PracticeNeetCode ↗LeetCode ↗
Given an m × n grid of heights, water flows from a cell to a neighbor whose height is less than or equal to its own, in four directions. The Pacific touches the top and left edges; the Atlantic touches the bottom and right edges. Return every coordinate from which water can reach both oceans.
pacific and atlantic, from their respective border cells (top row + left column; bottom row + right column).Time: O(rows · cols) — Space: O(rows · cols)
def pacificAtlantic(heights: list[list[int]]) -> list[list[int]]:
if not heights:
return []
rows, cols = len(heights), len(heights[0])
pacific, atlantic = set(), set()
def dfs(r: int, c: int, visited: set, prev_height: int) -> None:
if (r < 0 or r >= rows or c < 0 or c >= cols or
(r, c) in visited or heights[r][c] < prev_height):
return
visited.add((r, c))
for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
dfs(r + dr, c + dc, visited, heights[r][c])
for c in range(cols):
dfs(0, c, pacific, heights[0][c])
dfs(rows - 1, c, atlantic, heights[rows - 1][c])
for r in range(rows):
dfs(r, 0, pacific, heights[r][0])
dfs(r, cols - 1, atlantic, heights[r][cols - 1])
return [[r, c] for r in range(rows) for c in range(cols) if (r, c) in pacific and (r, c) in atlantic]How the solution above works, piece by piece.
dfs stops at the grid edge, at visited cells, or at cells lower than the one it came from (heights[r][c] < prev_height).pacific, and from the bottom row and right column into atlantic.Running it on an example grid heights = [[1, 2, 3], [8, 9, 4], [7, 6, 5]]: