Swim in Rising Water solution explained

Swim in Rising Water asks for the earliest time t at which you can get from the top-left cell of a square grid to the bottom-right cell, moving only through cells whose height is at most t. That is the same as finding the path whose highest cell is as low as possible, including both corner cells. Solve it with a Dijkstra-style search on a min-heap keyed by the highest cell seen so far, in O(n² log n) for an n by n grid, or by binary searching on t with a BFS at each step.

By Published 9 min read

The problem, restated

You get an n by n grid of non-negative integer heights. Rain raises the water to level t at time t, everywhere at once. You start in the top-left cell and may move up, down, left or right, any distance and instantly, as long as every cell you pass through, including where you stand, has height at most t. Return the smallest t at which you can reach the bottom-right cell. In the usual version all heights are different; nothing on this page depends on that.

Grids made up for this page
Grid (rows)AnswerWhy
[2, 6, 1] / [4, 8, 5] / [7, 3, 0]6Along the top and down the right side the highest cell is 6. Going down the left side passes 7, and the middle is 8.
[3, 9] / [1, 0]3The start cell itself is 3, so you cannot leave before t = 3.
[5]5A 1 by 1 grid: you must wait until the only cell is covered.
[0, 2] / [1, 3]3The target corner is 3, the highest cell, so its own height sets the answer.
Grids made up for this page. Scroll sideways on a small screen.

Why interviewers like it

It looks like a shortest-path problem but the cost of a path is its maximum, not its sum. The interviewer wants to see you reframe it that way, then pick a technique that fits a max-cost path. There are three good answers (a heap search, a binary search on the answer, and union-find), and being able to compare them is part of a strong performance. It is also a test of the small details: the start cell's own height, and the 1 by 1 grid.

Baseline: raise the water one step at a time

The answer is at least the higher of the two corner heights. Start t there and run a BFS that only enters cells with height at most t. If the target is not reached, add 1 and try again. With heights up to about n², this runs up to n² searches of n² cells each, O(n⁴). It is too slow for big grids but a clean reference to test against.

Binary search on the answer

Reachability is monotone in t: if you can cross at time t, you can cross at any later time, because the set of usable cells only grows. That is exactly the condition for binary searching on the answer. Search t between the start height and the maximum height, and at each step run the same BFS. Each check is O(n²), and the search takes about log of the height range steps, which is O(log n) when heights are bounded by n².

from collections import deque


def can_reach(grid, t):
    n = len(grid)
    if grid[0][0] > t:
        return False
    seen = [[False] * n for _ in range(n)]
    seen[0][0] = True
    queue = deque([(0, 0)])
    while queue:
        r, c = queue.popleft()
        if (r, c) == (n - 1, n - 1):
            return True
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < n and 0 <= nc < n and not seen[nr][nc] and grid[nr][nc] <= t:
                seen[nr][nc] = True
                queue.append((nr, nc))
    return False


def swim_binary_search(grid):
    lo, hi = grid[0][0], max(max(row) for row in grid)
    while lo < hi:                    # smallest t for which the corner is reachable
        mid = (lo + hi) // 2
        if can_reach(grid, mid):
            hi = mid
        else:
            lo = mid + 1
    return lo
Binary search on t with a BFS check. O(n² log n) when heights are at most n².

For the first grid, the checks are false for every t up to 5 and true from 6 on, so the search settles on 6. Note the lower bound: starting at grid[0][0] means can_reach never has to handle a start cell that is still dry, although the function checks it anyway.

Min-heap on the highest cell so far

Dijkstra's algorithm works for any path cost that never decreases as the path gets longer, and the maximum along a path has that property. Keep a min-heap of cells keyed by the highest height on the best known path to them. Pop the lowest, mark it settled, and push each unsettled neighbour with the key max(current key, neighbour height). The first time the target is popped, its key is the answer, because every other route has a key at least as high.

import heapq


def swim_in_water(grid):
    n = len(grid)
    best = [[None] * n for _ in range(n)]
    heap = [(grid[0][0], 0, 0)]       # (highest cell on the path so far, row, col)
    while heap:
        level, r, c = heapq.heappop(heap)
        if best[r][c] is not None:
            continue                  # already settled with a lower level
        best[r][c] = level
        if (r, c) == (n - 1, n - 1):
            return level
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < n and 0 <= nc < n and best[nr][nc] is None:
                heapq.heappush(heap, (max(level, grid[nr][nc]), nr, nc))
    return -1                         # not reached for a non-empty square grid
Dijkstra-style search with max instead of plus. O(n² log n).

On the first grid the heap pops 2 (the start), then 4 below it, then the 6 to its right. From there the keys stay at 6, because 1, 5 and 0 are all lower, and the search walks along the top and down the right side to the target with key 6. The 7 and 8 cells are pushed but never needed.

#include <algorithm>
#include <array>
#include <functional>
#include <queue>
#include <vector>
using namespace std;

int swimInWater(const vector<vector<int>>& grid) {
    int n = grid.size();
    vector<vector<bool>> done(n, vector<bool>(n, false));
    // min-heap of {level, row, col}; level = highest cell on the path so far
    priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> heap;
    heap.push({grid[0][0], 0, 0});
    const int dr[4] = {1, -1, 0, 0};
    const int dc[4] = {0, 0, 1, -1};
    while (!heap.empty()) {
        auto [level, r, c] = heap.top();
        heap.pop();
        if (done[r][c]) continue;
        done[r][c] = true;
        if (r == n - 1 && c == n - 1) return level;
        for (int k = 0; k < 4; k++) {
            int nr = r + dr[k], nc = c + dc[k];
            if (nr >= 0 && nr < n && nc >= 0 && nc < n && !done[nr][nc]) {
                heap.push({max(level, grid[nr][nc]), nr, nc});
            }
        }
    }
    return -1;
}
C++17 with a min-heap of {level, row, col}.

std::priority_queue is a max-heap by default, so the greater comparator flips it. Arrays of three ints compare element by element, which orders the heap by level first. A cell can be pushed more than once; the done check on pop skips the stale copies.

The union-find version, in words

Sort the cells by height. Add them one at a time, and each time union the new cell with any neighbour that is already added. As soon as the two corners are in the same set, the height of the cell just added is the answer. Sorting n² cells costs O(n² log n), and the unions are nearly constant each. When the heights are exactly 0 to n² - 1, you can skip the sort by storing the position of each height.

Complexity

n by n grid, so n² cells; H is the largest height
ApproachTimeExtra space
Raise t by one, BFS each timeO(n² · H), which is O(n⁴) when H ≈ n²O(n²)
Binary search on t with BFSO(n² log H)O(n²)
Min-heap searchO(n² log n)O(n²)
Union-find in height orderO(n² log n) with the sortO(n²)
n by n grid, so n² cells; H is the largest height. Scroll sideways on a small screen.

Edge cases

  • A 1 by 1 grid: the answer is that cell's height.
  • A high start cell: you cannot move until it is covered.
  • A high target cell: the answer is at least its height.
  • Repeated heights, if your version allows them: all three methods still work.
  • A single wall of high cells across the grid: the answer is the lowest gap in the wall or something higher on the way to it.

Mistakes

  • Starting the key at 0 instead of the start cell's height.
  • Adding heights along the path as in ordinary Dijkstra instead of taking the maximum.
  • Marking cells settled when pushed instead of when popped, which can lock in a worse key.
  • Binary searching from 0 to n² without noting that heights may be larger in other versions; use the real maximum.
  • Using a max-heap in C++ by forgetting the comparator.
  • Allowing diagonal moves.

How to explain it out loud

Fictional example

Naming it a bottleneck path
Candidate
At time t I can use any cell up to height t, so the answer is the lowest possible value of the highest cell on some path, counting both corners.
Candidate
That's a path cost that never goes down as the path grows, so Dijkstra works with max in place of plus. I'll keep a min-heap keyed by the highest cell so far and stop when I pop the target.
Interviewer
Any other approach?
Candidate
Binary search on t, since if I can cross at t I can cross later. Each check is a BFS over n squared cells. Both are n squared log n; the heap version stops as soon as it reaches the corner.

Grid BFS is the same machinery as in Number of Islands, and the union-find variant reuses what you build for Accounts Merge and Evaluate Division. For the heap itself, Find Median from Data Stream is good practice. On dependency graphs instead of grids, topological sort is the next technique, and Find the Town Judge is a quick warm-up on directed edges.

Running through it with Natively

With three valid methods, it helps to see each one laid out next to your own. Natively can read the grid problem from a screenshot on Mac or Windows and show an approach and code in its overlay, so you can check your heap key and your settled check. Practicing out loud, you get a transcript of the session to review your explanation of why max replaces plus. Learn more on the AI interview assistant page.

Questions people ask

How do you solve Swim in Rising Water?

Find the path from corner to corner whose highest cell is lowest. Use a min-heap keyed by the highest cell seen so far, expand the lowest key first, and return the key when the target is popped.

Why does Dijkstra work for Swim in Rising Water?

Dijkstra needs a path cost that never decreases as a path gets longer. The maximum height along a path has that property, so you use max instead of plus.

Can you use binary search for Swim in Rising Water?

Yes. If you can cross at time t you can cross at any later time, so binary search on t and check each guess with a BFS over cells of height at most t.

What is the time complexity of Swim in Rising Water?

O(n² log n) for an n by n grid with the min-heap, and O(n² log H) with binary search, where H is the largest height. Space is O(n²).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP