Skip to main content
← Swim in Rising Water problem

Swim in Rising Water worked solution

Swim in Rising Water video walkthrough

Playing shares your IP address with Google and may use device storage. By playing, you agree to our privacy notice and YouTube’s terms. Google privacy

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 water level 3 the left column is connected but the wet finish is isolated. At level 4 the new square connects the bottom row and completes the route.
Follow the joined squares from 0 down to 2. The only new square at level 4 is the one between 2 and the finish.
  1. 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.
  2. 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?
Reading note

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.

After crossing elevation 4, the required water level stays at 4 over the lower finish.
The ground falls from 4 to 3 on the last move. The blue line stays at 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 answer

Swim 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?
Reading note

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.

Two routes each use two moves, but the upper route requires level 3 and the lower route requires only 2.
Start at 0 and finish at 1. Two equally short routes can require different water levels.

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 answer

Python 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)

Try the rising-water grid

Set the water level to 3, then 4. Switch to the heap trace to see which squares the search reaches first.

At t = 3, the finish cell (elevation 3) is underwater — yet blocked by elevation 4 at (2, 1)! Path opens at t = 4.

Step 1 of 6 · Current water level: t = 0Start (0,0) → Goal (2,2)
START0best: 0
(0,1)6best: ∞
(0,2)7best: ∞
(1,0)1best: ∞
(1,1)5best: ∞
(1,2)8best: ∞
(2,0)2best: ∞
(2,1)4best: ∞
GOAL3best: ∞

Algorithm State Inspector

Initialize best[0][0] = 0 and push (0, 0, 0) onto the min-heap.

Min-Heap Queue (level, row, col)1 entries
(0, 0, 0)
Key Minimax Invariant: Standard Dijkstra relaxes with cost + weight. Here, swimming is instant once water reaches height t, so path cost is max(level, grid[nr][nc]) — still monotonically non-decreasing, which is why Dijkstra’s greedy first-pop guarantee holds!
Learn These Concepts Before SolvingStudy highlighted concepts first
→Binary Heaps & Top-K→Dijkstra’s Algorithm→Minimax PathsComing soon→Grid GraphComing soon

Practise first with Path With Minimum Effort

Sliding Puzzle walkthrough →

← Back to practice

Opening sign-in…