Skip to content

Swim in Rising Water

Find the earliest time you can swim from one corner of a grid to the other as the water rises.

HardShortest Paths
Solve on LeetCode

The problem

You get an n x n grid where grid[r][c] is the height of that cell, and the heights are the numbers 0 to n^2 - 1 in some order. At time t the water everywhere is at level t, and you can swim between two cells that share a side only if both heights are at most t. Swimming itself takes no time. Return the earliest time at which you can get from the top-left cell to the bottom-right cell.

Input grid = [[0, 6, 2], [8, 4, 1], [3, 7, 5]]

Output 6

Every route leaves the start through 6 or 8, so nothing moves before t = 6. At t = 6 you can swim 0, 6, 2, 1, 5.

Input grid = [[3, 1], [2, 0]]

Output 3

You stand on height 3, so you can't leave the start before t = 3.

Key constraint: The time a route needs is its highest cell, so you want the route whose highest cell is as low as possible.

How to spot the pattern

  • The cost of a route is its single worst cell, not a sum.
  • You need the best route between two corners of a grid with moves in 4 directions.
  • Waiting never hurts: anything you can reach at time t you can still reach later.

The idea

On any route you must wait until the water covers its highest cell, so the answer is the smallest possible maximum height along a route from corner to corner. Dijkstra handles that if a route's cost is its highest cell so far: stepping onto a cell of height h with cost t gives cost max(t, h). Always expand the cheapest frontier cell from a min-heap, and the cost when you first pop the bottom-right cell is the answer.

Brute force: Try every time t from 0 upward and run a BFS over the cells of height at most t, which takes O(n^4) time.

Step by step

  1. 1Keep best[r][c], the earliest time found so far for each cell, start it at grid[0][0] for the start cell, and push (grid[0][0], 0, 0) onto a min-heap.
  2. 2Pop the entry with the smallest time t; if it is the bottom-right cell, return t.
  3. 3Skip the entry if t is larger than best for its cell, because that cell was reached earlier.
  4. 4For each of the 4 neighbors, the time through this cell is max(t, neighbor height); if it beats the neighbor's best, store it and push the neighbor.

See the pattern move

The shortest paths pattern on a small example. Step through it, or press play.

Code

import heapq


class Solution:
    def swimInWater(self, grid: List[List[int]]) -> int:
        n = len(grid)
        # best[r][c] = earliest time found so far at which you can stand on (r, c)
        best = [[float("inf")] * n for _ in range(n)]
        best[0][0] = grid[0][0]
        heap = [(grid[0][0], 0, 0)]  # (time, row, col), smallest time first
        while heap:
            t, r, c = heapq.heappop(heap)
            if r == n - 1 and c == n - 1:
                return t
            if t > best[r][c]:
                continue  # an old entry; this cell was reached earlier
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < n and 0 <= nc < n:
                    # you must wait until the water covers the higher of the two
                    new_time = max(t, grid[nr][nc])
                    if new_time < best[nr][nc]:
                        best[nr][nc] = new_time
                        heapq.heappush(heap, (new_time, nr, nc))
        return -1

Complexity

Time

O(n^2 log n)

Space

O(n^2)

There are n^2 cells, each pushed at most once per neighbor, and a heap operation costs O(log n^2), which is O(log n).

Watch out for

  • Forgetting the start cell's own height: you can't leave it before t = grid[0][0].
  • Adding heights along the route like a normal shortest path; the time is the maximum, not the sum.
  • Moving only right and down: the lowest route may have to go up or left around a high block.

Follow-up questions

Can you solve it with binary search?

Yes. For a guess t, a BFS that only enters cells of height at most t tells you if you can cross. The smallest t that works is the answer, found in O(n^2 log n) time.

How would union-find solve it?

Add cells in order of height and join each new cell with its neighbors that are already added. The height at which the two corners first land in the same group is the answer.

In Hinglish

Kisi bhi raaste ka time uski sabse oonchi cell hai. Dijkstra chalao jismein cost `max(t, height)` ho, aur bottom-right cell heap se jab pehli baar nikle, wahi jawab hai.

Related problems