Swim in Rising Water (LeetCode 778): Solution and Explanation

Hard
Array
Binary Search
Depth First Search
Breadth First Search
Union Find
Heap
Matrix

An n by n grid holds distinct elevations from 0 to n² - 1. At time t you can move between adjacent cells only if both elevations are at most t, and swimming itself takes no time. Return the earliest time at which you can get from the top-left to the bottom-right corner.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Rephrase the goal: find the smallest t such that a path exists using only cells with elevation at most t. Equivalently, minimize the highest cell on the path. Trying every path is exponential, but there is a powerful monotonic property hiding here.

If you can make it at time t, you can certainly make it at any later time, because rising water only opens more cells. That means the answer to "can I reach the end by time t" is false for small t and true from some point on. Whenever a yes or no question flips exactly once like that, binary search finds the flip point.

The answer must lie between grid[0][0], since you are standing on that cell, and n * n - 1, the highest elevation. For each candidate mid, run a flood fill from the start that only steps onto cells with elevation at most mid. If it reaches the corner, the answer is mid or smaller; otherwise it is larger.

Approach: Binary search on time with DFS reachability

  1. Define canReach(t): if grid[0][0] > t return false, otherwise run an iterative DFS from (0, 0) with a visited grid.
  2. In the DFS, return true as soon as the bottom-right cell is popped, and only push unvisited neighbors with grid[nx][ny] <= t, marking them visited when pushed.
  3. Set left = grid[0][0] and right = n * n - 1.
  4. While left < right, test mid = (left + right) // 2. If canReach(mid) succeeds, set right = mid; otherwise set left = mid + 1.
  5. Return left, the smallest time that works.

Step-by-step example

grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
  1. The search starts with left = 0 and right = 24. mid = 12 fails: the top row and the 5 are open, but 16 and 21 block every way down.
  2. left = 13, so mid = 18. Now the snake 5, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6 is open, the DFS reaches the corner, and right = 18.
  3. mid = 15 fails because the cell with 16 is the only way from the 5 into the lower rows, so left = 16.
  4. mid = 17 succeeds, so right = 17. Then mid = 16 succeeds, so right = 16.
  5. left and right meet at 16, which is the answer: the highest cell on the best path is the 16.

Code: Python, Java, C++

1class Solution:
2    def swimInWater(self, grid: List[List[int]]) -> int:
3        n = len(grid)
4
5        def canReach(t):
6            if grid[0][0] > t:
7                return False
8            visited = [[False] * n for _ in range(n)]
9            stack = [(0, 0)]
10            visited[0][0] = True
11            while stack:
12                x, y = stack.pop()
13                if x == n - 1 and y == n - 1:
14                    return True
15                for dx, dy in [(0,1),(0,-1),(1,0),(-1,0)]:
16                    nx, ny = x + dx, y + dy
17                    if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny] and grid[nx][ny] <= t:
18                        visited[nx][ny] = True
19                        stack.append((nx, ny))
20            return False
21
22        left, right = grid[0][0], n * n - 1
23        while left < right:
24            mid = (left + right) // 2
25            if canReach(mid):
26                right = mid
27            else:
28                left = mid + 1
29        return left

Time and space complexity

Time

O(n² log n)

Each canReach call visits at most n² cells, and binary search over a range of size n² takes O(log(n²)) = O(log n) iterations.

Space

O(n²)

Each check allocates an n by n visited grid and a stack that can hold most of the cells.

Other approaches

Dijkstra or min-heap flood (time O(n² log n), space O(n²))

Expand from the start with a min-heap keyed by elevation, always taking the lowest reachable cell, and track the highest elevation popped so far. When the corner is popped, that maximum is the answer.

Union-find in elevation order (time O(n² α(n²)), space O(n²))

Process cells from lowest to highest elevation, union each with already-active neighbors, and stop when the two corners are connected. The elevation just processed is the answer.

Common mistakes

  • Setting the lower bound to 0 instead of grid[0][0], or forgetting the start check in canReach. You cannot leave the start before the water covers it.
  • Using right = mid - 1 when a check succeeds. mid itself might be the answer, so it must stay in range.
  • Marking cells visited only when popped, which lets the same cell be pushed many times and slows each check.
  • Reusing one visited grid across checks without resetting it, so later checks think cells are already explored.

Frequently asked questions

Why can Swim in Rising Water use binary search?

Reachability is monotonic in time: if you can reach the corner at time t, you can at every later time, since rising water only opens cells. Binary search finds the first time where the check turns true.

What is the time complexity of Swim in Rising Water?

With binary search and DFS it is O(n² log n): each check is O(n²) and there are O(log n) checks. The heap-based approach has the same bound.

Is this the same as Path With Minimum Effort?

They are close cousins. Both minimize a maximum along a path, but here the cost is the highest cell elevation, while minimum effort uses the largest height difference between neighbors.

Should I use Dijkstra or binary search?

Either is fine. Dijkstra stops as soon as it reaches the corner, while binary search with DFS is simple to write and easy to reason about.