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 flow from a cell to neighboring cells directly north, south, east, and west if the neighboring cell’s height is less than or equal to the current cell’s height.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.
pacific_reachable
and atlantic_reachable
) to mark cells reachable from each ocean.def pacificAtlantic(heights):
if not heights or not heights[0]:
return []
m, n = len(heights), len(heights[0])
# Initialize reachable matrices
pacific_reachable = [[False for _ in range(n)] for _ in range(m)]
atlantic_reachable = [[False for _ in range(n)] for _ in range(m)]
# Directions for movement: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(x, y, reachable):
reachable[x][y] = True
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and not reachable[nx][ny] and heights[nx][ny] >= heights[x][y]:
dfs(nx, ny, reachable)
# Start DFS from Pacific Ocean boundaries
for i in range(m):
dfs(i, 0, pacific_reachable)
dfs(i, n - 1, atlantic_reachable)
for j in range(n):
dfs(0, j, pacific_reachable)
dfs(m - 1, j, atlantic_reachable)
# Collect results
result = []
for i in range(m):
for j in range(n):
if pacific_reachable[i][j] and atlantic_reachable[i][j]:
result.append([i, j])
return result
pacific_reachable
and atlantic_reachable
matrices and the recursion stack.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?