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. Tags: Graph
Try It!
Discussion
Video
Solution
class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
if not matrix:
return []
m = len(matrix)
n = len(matrix[0])
p_visited = [[False for c in range(n)] for r in range(m)]
a_visited = [[False for c in range(n)] for r in range(m)]
res = []
for r in range(m):
self.dfs(matrix, r, 0, p_visited, m, n)
self.dfs(matrix, r, n - 1, a_visited, m, n)
for c in range(n):
self.dfs(matrix, 0, c, p_visited, m, n)
self.dfs(matrix, m - 1, c, a_visited, m, n)
for r in range(m):
for c in range(n):
if p_visited[r][c] and a_visited[r][c]:
res.append([r, c])
return res
def dfs(self, matrix, r, c, visited, m, n):
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited[r][c] = True
for direction in directions:
next_r = r + direction[0]
next_c = c + direction[1]
if next_r < 0 or next_r >= m:
continue
if next_c < 0 or next_c >= n:
continue
if visited[next_r][next_c]:
continue
if matrix[next_r][next_c] < matrix[r][c]:
continue
self.dfs(matrix, next_r, next_c, visited, m, n)