Swim in Rising Water (LeetCode 778): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Define
canReach(t): ifgrid[0][0] > treturn false, otherwise run an iterative DFS from (0, 0) with a visited grid. - 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. - Set
left = grid[0][0]andright = n * n - 1. - While
left < right, testmid = (left + right) // 2. IfcanReach(mid)succeeds, setright = mid; otherwise setleft = mid + 1. - 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]]
- The search starts with
left = 0andright = 24.mid = 12fails: the top row and the 5 are open, but 16 and 21 block every way down. left = 13, somid = 18. Now the snake 5, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6 is open, the DFS reaches the corner, andright = 18.mid = 15fails because the cell with 16 is the only way from the 5 into the lower rows, soleft = 16.mid = 17succeeds, soright = 17. Thenmid = 16succeeds, soright = 16.leftandrightmeet 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 left1class Solution {
2 public int swimInWater(int[][] grid) {
3 int n = grid.length;
4 int left = grid[0][0], right = n * n - 1;
5 while (left < right) {
6 int mid = (left + right) / 2;
7 if (canReach(grid, mid)) right = mid;
8 else left = mid + 1;
9 }
10 return left;
11 }
12
13 boolean canReach(int[][] grid, int t) {
14 int n = grid.length;
15 if (grid[0][0] > t) return false;
16 boolean[][] visited = new boolean[n][n];
17 Deque<int[]> stack = new ArrayDeque<>();
18 stack.push(new int[]{0, 0});
19 visited[0][0] = true;
20 int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};
21 while (!stack.isEmpty()) {
22 int[] cell = stack.pop();
23 if (cell[0] == n - 1 && cell[1] == n - 1) return true;
24 for (int[] d : dirs) {
25 int nx = cell[0] + d[0], ny = cell[1] + d[1];
26 if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] <= t) {
27 visited[nx][ny] = true;
28 stack.push(new int[]{nx, ny});
29 }
30 }
31 }
32 return false;
33 }
34}1class Solution {
2public:
3 int swimInWater(vector<vector<int>>& grid) {
4 int n = grid.size();
5 int left = grid[0][0], right = n * n - 1;
6 while (left < right) {
7 int mid = (left + right) / 2;
8 if (canReach(grid, mid)) right = mid;
9 else left = mid + 1;
10 }
11 return left;
12 }
13
14 bool canReach(vector<vector<int>>& grid, int t) {
15 int n = grid.size();
16 if (grid[0][0] > t) return false;
17 vector<vector<bool>> visited(n, vector<bool>(n, false));
18 stack<pair<int,int>> stk;
19 stk.push({0, 0});
20 visited[0][0] = true;
21 int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
22 while (!stk.empty()) {
23 auto [x, y] = stk.top(); stk.pop();
24 if (x == n - 1 && y == n - 1) return true;
25 for (auto& d : dirs) {
26 int nx = x + d[0], ny = y + d[1];
27 if (nx >= 0 && nx < n && ny >= 0 && ny < n && !visited[nx][ny] && grid[nx][ny] <= t) {
28 visited[nx][ny] = true;
29 stk.push({nx, ny});
30 }
31 }
32 }
33 return false;
34 }
35};Time and space complexity
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.
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 incanReach. You cannot leave the start before the water covers it. - Using
right = mid - 1when a check succeeds.miditself 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.