Pacific Atlantic Water Flow
Find the cells whose water can reach both ditches
DSA, Medium, Graphs
Which structure or algorithm, and what does it cost.
A field is a grid of ground heights. Rain on a cell runs to a side neighbour of the same height or lower. Ditch A runs along the west and north edges. Ditch B runs along the east and south edges. Rain on an edge cell reaches that edge's ditch at once, and a corner touches two edges. Write both_ditches(heights). It returns every cell whose rain can reach both ditches, as [row, column] pairs ordered by row, then by column.
Examples
Constraints
- 1 <= rows <= 200 and 1 <= columns <= 200.
- 0 <= height <= 1,000.
- All rows have the same length.
Your answer must contain
- Why the search runs backwards from the edges; the method; code; time and memory cost; a hand trace of example 1; a single cell.
Target Aim for O(R * C) time and memory, where R is the number of rows and C the number of columns.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Pick one ditch. Which cells are sure to reach it? Which other cells reach it because their rain can run into one of those cells?
Hint 2 the approach
Search outward from the ditch edges instead of from every cell. The cells you find are exactly the ones whose rain drains into that ditch.
Hint 3 the key step
Run one search per ditch, starting from all its edge cells at once. Step only to a neighbour at the same height or higher. Keep the cells both searches found.
Walkthrough
Full walkthrough brute force to best
Brute force
For every cell, search downhill through neighbours of the same height or lower, and note whether the search touches the west or north edge and whether it touches the east or south edge. One search can visit all R * C cells, so this costs O((R * C)^2) time.
Best method
Turn the question around. Rain on a cell reaches ditch A exactly when you can walk from an edge of ditch A to that cell by steps that never go down. So start one search from all cells on the west and north edges. From a cell, step to a side neighbour whose height is the same or higher, because rain on that neighbour runs into this cell. The cells found drain into ditch A. Run the same search from the east and south edges to find the cells that drain into ditch B. Keep the cells in both sets and sort them. Each search visits a cell at most once.
Hand trace
Example 1: search A starts from (0,0), (1,0), (2,0), (0,1), (0,2) and (0,3). It climbs to equal or higher neighbours and reaches 10 cells: every cell except (2,2) and (2,3). Search B starts from (0,3), (1,3), (2,3), (2,0), (2,1) and (2,2). It reaches 8 cells: (0,3), (1,0), (1,2), (1,3), (2,0), (2,1), (2,2) and (2,3). The cells in both sets, in order, are (0,3), (1,0), (1,2), (1,3), (2,0) and (2,1).
Code
from collections import deque
def both_ditches(heights):
rows, cols = len(heights), len(heights[0])
def reach(starts):
# search backwards: step to a neighbour that is the same height or higher
seen = set(starts)
todo = deque(starts)
while todo:
r, c = todo.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen and heights[nr][nc] >= heights[r][c]:
seen.add((nr, nc))
todo.append((nr, nc))
return seen
west_north = [(r, 0) for r in range(rows)] + [(0, c) for c in range(1, cols)]
east_south = [(r, cols - 1) for r in range(rows)] + [(rows - 1, c) for c in range(cols - 1)]
return [[r, c] for r, c in sorted(reach(west_north) & reach(east_south))]Time and memory
O(R * C) time and O(R * C) memory. Each search marks each cell at most once and looks at four neighbours. The two sets and the queue hold up to R * C cells.
Common mistakes
- Stepping to lower neighbours when you search backwards from the ditch. Going backwards, you step to the same height or higher.
- Using strictly higher. Level ground lets rain pass, so a neighbour of the same height counts.
- Starting a search from only one row or column of an edge. A ditch edge has a whole row and a whole column, and a corner belongs to both.
- Returning the cells in the order the search found them. The answer must be sorted by row, then by column.