Swim In Rising Water
Find the first hour a swimmer can cross the flooded field
DSA, Hard, Advanced Graphs
Which structure or algorithm, and what does it cost.
A flooded field is an n by n grid of squares. ground[r][c] is the height of one square's ground. The water level starts at 0 and rises by 1 every hour, everywhere at once. A swimmer can enter a square only when the water level is at least its ground height. The swimmer starts in the top-left square and wants the bottom-right square, moving up, down, left or right. Swimming takes no time: the swimmer can cross any number of open squares at once. Return the first hour when the swimmer can arrive. Squares may share a height.
Examples
Constraints
- 1 <=
n<= 300. - 0 <= ground height of a square <= 1,000,000.
Your answer must contain
- Why a route costs its highest square and not the sum; the method; code; time and memory cost; a hand trace of example 1; the edge cases.
Target Aim for O(n^2 log n) time and O(n^2) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
The water must cover every square on the swimmer's route. So each route has one hour that matters. Which hour is it?
Hint 2 the approach
Compare routes by their highest square, not by their length. Explore from the start, always continuing from the square that keeps the highest value lowest.
Hint 3 the key step
Keep a min-heap of squares, each keyed by the highest ground on the best route found to it. Pop the smallest. Stop when you pop the bottom-right square.
Walkthrough
Full walkthrough brute force to best
Brute force
List every route from the top-left square to the bottom-right square that never repeats a square. Note the highest square on each route and take the smallest of those. The number of routes grows exponentially with the size of the field.
Better method
Binary search on the hour H. For a guess H, flood fill from the start over squares with ground height at most H and check whether the finish is reached. If it is, try a smaller H. If not, try a larger one. This costs O(n^2 log V) time, where V is the largest height: about 20 flood fills of n^2 squares.
Best method
A route costs its highest square, so you want the route whose maximum is smallest. Keep a min-heap of squares, each with the highest ground on the best route found to it so far. Start with the top-left square at its own height. Pop the smallest entry. If its square is already done, skip it. Mark it done. If it is the bottom-right square, return its value. Otherwise push each square next to it that is not done, with the larger of the popped value and that square's height. The first time a square is popped, its value is the smallest possible: every other route to it passes through a heap entry that is at least as large, and a maximum never makes a route lower. This is Dijkstra's algorithm with a maximum in place of a sum.
Hand trace
Example 1: push (5, row 0, column 0). Pop it and push (7, 1, 0) and (9, 0, 1). Pop (7, 1, 0) and push (7, 2, 0) and (7, 1, 1). Pop (7, 1, 1) and push (7, 2, 1), (9, 0, 1) and (8, 1, 2). Pop (7, 2, 0) and push (7, 2, 1). Pop (7, 2, 1) and push (7, 2, 2). Pop the second (7, 2, 1): its square is already done, so skip it. Pop (7, 2, 2). It is the finish square, so return 7.
Code
import heapq
def swim_hour(ground):
n = len(ground)
done = [[False] * n for _ in range(n)]
heap = [(ground[0][0], 0, 0)] # (highest square on the best route so far, row, column)
while heap:
t, r, c = heapq.heappop(heap)
if done[r][c]:
continue
done[r][c] = True
if (r, c) == (n - 1, n - 1):
return t
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and not done[nr][nc]:
heapq.heappush(heap, (max(t, ground[nr][nc]), nr, nc))Time and memory
O(n^2 log n) time: there are n^2 squares, each is pushed up to 4 times, and each heap step costs O(log n). O(n^2) memory for the done marks and the heap.
Common mistakes
- Adding up the heights along the route. The water only has to reach the highest square, so use a maximum.
- Forgetting the start square. Its height counts, so with n = 1 the answer is the height of that one square.
- Allowing only right and down moves. The best route can go up or left around high ground.