Worked solution
What are we minimising?
Imagine standing on a low patch of ground and watching the far corner disappear under water. You still can’t swim there. A ridge between you and the corner is dry. How high does the water have to rise before there’s a way through?
A route opens as soon as its highest square is underwater. After that you can swim its entire length at once. If one route crosses a ridge of height 8 and another stays at or below 4, the second opens four minutes earlier. Finding the best route means finding the lowest such ridge. This is sometimes called a minimax path.
The finish is at 3. Why is the answer 4?
Start at 0 in the top left and aim for 3 in the bottom right. Read the numbers as elevations. The same grid is shown twice so you can see exactly what changes when the water rises one more unit.
- At level 3, you can swim down through 0, 1 and 2. Every crossing into the middle column is still dry. Even though the finish is wet, it’s out of reach.
- At level 4, swim from 2 across to 4, then on to 3. You’ve found a route that works at 4 and shown why 3 was too early.
How does the heap find that route?
Dijkstra’s algorithm keeps the cheapest known way to reach each square. Here its price is a water level. To extend a route, take the larger of the level it already needs and the next square’s elevation.
From 0, the heap offers 1 below or 6 to the right. It takes 1, which leads to 2. From 2 it can offer 4. When the search crosses from 4 to 3, the required level stays at 4. A min-heap always takes the lowest available level, and extending a route can only keep or raise that level. When the finish comes out at 4, every cheaper possibility has had its turn.
Side note Why take the maximum elevation along the route?
Why take the maximum elevation along the route?
Suppose you have just crossed elevation 4 and the finish is a step away at elevation 3. The clock reads 4. The finish is already underwater and the last stroke takes zero time, so you arrive at time 4.
That gives a rule you can use on any route. If the next square is lower than the water you already needed, you can cross immediately. If it is higher, wait until the water reaches it. The highest square you have crossed sets the clock.
Use max(current level, next elevation) for each move. The starting square counts too, so initialise the heap with its elevation.
LeetCode’s movement and timing rules
Link to this answerSwim in Rising Water time and space complexity
On an n × n grid, each of the n² squares has at most four neighbours. Dijkstra settles each square once. Inserting or removing a heap entry takes O(log n²), which gives O(n² log n) time. The best-level table and the heap together use O(n²) space.
Another approach opens the squares in elevation order and joins neighbouring open regions with union-find. The starting and finishing squares first share a region at the answer. You can also test one water level at a time with breadth-first search.
Side note Can breadth-first search find the earliest crossing?
Can breadth-first search find the earliest crossing?
BFS on the whole grid finds the fewest strokes. In this little grid, right then down and down then right both use two strokes. One goes through elevation 3 and the other through 2. An ordinary BFS can return either.
BFS can answer a different question exactly. Pick a water level and visit only squares at or below it. At level 1 the finish is cut off. At level 2 the lower route opens. Once a route opens, it stays open at every higher level.
Binary search can find the first level where this BFS succeeds. It takes O(n² log n) time and O(n²) space for an n × n grid with distinct elevations from 0 through n² − 1.
NeetCode’s binary search and flood-fill solution
Link to this answerPython solution for Swim in Rising Water
Each heap entry holds the required level, row and column. Start with the elevation under your feet. When a route improves the best level for a neighbour, save it and push that neighbour onto the heap.
from heapq import heappop, heappush
def swim_in_water(grid: list[list[int]]) -> int:
n = len(grid)
best = [[float("inf")] * n for _ in grid]
best[0][0] = grid[0][0]
heap = [(grid[0][0], 0, 0)]
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
while heap:
level, r, c = heappop(heap)
if level != best[r][c]:
continue
if (r, c) == (n - 1, n - 1):
return level
for dr, dc in directions:
nr, nc = r + dr, c + dc
if not (0 <= nr < n and 0 <= nc < n):
continue
candidate = max(level, grid[nr][nc])
if candidate < best[nr][nc]:
best[nr][nc] = candidate
heappush(heap, (candidate, nr, nc))
raise ValueError("Grid must be non-empty")
class Solution:
def swimInWater(self, grid: list[list[int]]) -> int:
return swim_in_water(grid)