417. Pacific Atlantic Water Flow
There is an m x n
rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The rain water can flow to neighboring cells if the neighboring cell's height is less than or equal to the current cell's height.
Return a 2D list of coords from that rain water can flow from cell (ri, ci)
to both oceans.
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
def can_flow(sr, sc, dr, dc):
return heights[sr][sc] >= heights[dr][dc]
qp = deque(), qa = deque()
R, C = len(heights), len(heights[0])
for c in range(C):
qp.append((0, c))
for r in range(R):
qp.append((r, 0))
for r in range(R):
qa.append((r, C-1))
for c in range(C):
qa.append((R-1, c))
def is_valid(r, c):
return r >=0 and c >= 0 and r < R and c < C
def check_ocean(q, ocean):
dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]
while q:
r,c = q.popleft()
ocean.add((r, c))
nei = [(r+dr, c+dc) for dr, dc in dirs]
for nr, nc in nei:
if is_valid(nr, nc) and (nr, nc) not in ocean and can_flow(nr, nc, r, c):
q.append((nr, nc))
pacific = set()
check_ocean(qp, pacific)
atlantic = set()
check_ocean(qa, atlantic)
return list(pacific.intersection(atlantic))
Comments
Post a Comment