Swim in Rising Water
Hard
Topics
You are given an n x n grid where grid[i][j] is the elevation at that cell. At time t the water level is t, and you can move between two adjacent cells if both elevations are at most t. Starting at the top-left, return the least time to reach the bottom-right.
Example 1
At time
t you may stand on any cell of height ≤ t. The answer is the smallest t that connects the corners — 3 here — so what matters is the highest cell on the route, not the sum of the route.2D grid — one row per line.
Input: grid = [[0,2],[1,3]] Output: 3
Example 2
Input: 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]] Output: 16
Constraints
- 1 <= n <= 50
- grid holds a permutation of 0 .. n^2 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The cost of a path is the maximum elevation on it, and you want the path that minimizes that maximum. This is a shortest-path where "distance" is a max, so a Dijkstra-style min-heap keyed by the running max works.
Approach
- Use a min-heap of
(elevation-so-far, r, c)starting at the top-left. - Always pop the cell reachable with the smallest peak elevation.
- When you pop the bottom-right, that peak is the answer. Alternatively binary search t + BFS.
Dry Run
grid = [[0, 2],
[1, 3]] target is the bottom-right cell
heap entries are (time, row, col). time is the HIGHEST cell on the path so far.
start heap=[(0,0,0)]
pop (0,0,0) not the target
(1,0) holds 1 push (max(0,1), 1,0) = (1,1,0)
(0,1) holds 2 push (max(0,2), 0,1) = (2,0,1)
heap=[(1,1,0) (2,0,1)]
pop (1,1,0) not the target
(1,1) holds 3 push (max(1,3), 1,1) = (3,1,1)
heap=[(2,0,1) (3,1,1)]
pop (2,0,1) not the target, (1,1) already seen
heap=[(3,1,1)]
pop (3,1,1) bottom-right return 3
answer 3
The whole problem is in `max(t, grid[nr][nc])`. A path's cost is its single
worst cell, not the sum of its cells -- so this is Dijkstra with addition
replaced by max. That still works because extending a path can never lower its
worst cell, which is the only property Dijkstra actually needs.Complexity
- Time — O(n^2 log n): each cell is pushed once; heap ops are log of the number of cells.
- Space — O(n^2): the visited set and heap.
Common Pitfalls
- The path cost is the max cell on the path, not the sum — carry
max(t, elevation)in the heap.
Full Solution — all languages
class Solution:
def swimInWater(self, grid):
import heapq
n=len(grid)
seen={(0,0)}
heap=[(grid[0][0],0,0)]
while heap:
t,r,c=heapq.heappop(heap)
if r==n-1 and c==n-1: return t
for dr,dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr,nc=r+dr,c+dc
if 0<=nr<n and 0<=nc<n and (nr,nc) not in seen:
seen.add((nr,nc)); heapq.heappush(heap,(max(t,grid[nr][nc]),nr,nc))
return grid[0][0]import java.util.*;
class Solution {
public int swimInWater(int[][] grid) {
int n=grid.length;
boolean[][] seen=new boolean[n][n];
PriorityQueue<int[]> pq=new PriorityQueue<>((x,y)->x[0]-y[0]);
pq.add(new int[]{grid[0][0],0,0});
seen[0][0]=true;
int[] dr={1,-1,0,0},dc={0,0,1,-1};
while(!pq.isEmpty()) {
int[] cur=pq.poll();
int t=cur[0],r=cur[1],c=cur[2];
if(r==n-1&&c==n-1)return t;
for(int d=0;d<4;d++) {
int nr=r+dr[d],nc=c+dc[d];
if(nr>=0&&nr<n&&nc>=0&&nc<n&&!seen[nr][nc]) {
seen[nr][nc]=true;
pq.add(new int[]{Math.max(t,grid[nr][nc]),nr,nc});
}
}
}
return grid[0][0];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int swimInWater(vector<vector<int>>& grid) {
int n=grid.size();
vector<vector<char>> seen(n,vector<char>(n,0));
priority_queue<array<int,3>,vector<array<int,3>>,greater<array<int,3>>> pq;
pq.push({grid[0][0],0,0});
seen[0][0]=1;
int dr[]={1,-1,0,0},dc[]={0,0,1,-1};
while(!pq.empty()) {
auto cur=pq.top();
pq.pop();
int t=cur[0],r=cur[1],c=cur[2];
if(r==n-1&&c==n-1)return t;
for(int d=0;d<4;d++) {
int nr=r+dr[d],nc=c+dc[d];
if(nr>=0&&nr<n&&nc>=0&&nc<n&&!seen[nr][nc]) {
seen[nr][nc]=1;
pq.push({max(t,grid[nr][nc]),nr,nc});
}
}
}
return grid[0][0];
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var swimInWater = function(grid) {
const n=grid.length,seen=[];
for(let i=0;i<n;i++)seen.push(new Array(n).fill(false));
const heap=[[grid[0][0],0,0]];
seen[0][0]=true;
const dirs=[[1,0],[-1,0],[0,1],[0,-1]];
while(heap.length) {
heap.sort((x,y)=>x[0]-y[0]);
const top=heap.shift();
const t=top[0],r=top[1],c=top[2];
if(r===n-1&&c===n-1)return t;
for(const d of dirs) {
const nr=r+d[0],nc=c+d[1];
if(nr>=0&&nr<n&&nc>=0&&nc<n&&!seen[nr][nc]) {
seen[nr][nc]=true;
heap.push([Math.max(t,grid[nr][nc]),nr,nc]);
}
}
}
return grid[0][0];
};