Swim in Rising Water
Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #778
grid[i][j] is the elevation of a cell. At time t the water depth everywhere is t, and you can swim between 4-adjacent cells if both have elevation ≤ t. Swimming itself takes no time. Return the earliest time at which you can get from (0,0) to (n−1,n−1).
Examples
[[0,2],[1,3]] → 3
[[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]] → 16Hints
- The time a path needs is the maximum elevation on it, so you want the path whose max is smallest.
- This is the same minimax shape as Path With Minimum Effort, but with node weights instead of edge weights.
Approach
Dijkstra / best-first search: the heap holds (maxSoFar, r, c), starting from (grid[0][0], 0, 0). Pop the smallest, and push each unseen neighbor with max(maxSoFar, grid[nr][nc]). The first time you pop the target, that value is the answer.
Since values are a permutation of 0..n²−1, two alternatives also work: binary-search t with a BFS check (O(n² log n)), or union-find adding cells in increasing elevation until the corners connect.
Complexity
Time: O(n² log n). Space: O(n²).
Python solution
import heapq
def swimInWater(grid):
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 nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
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))JavaScript solution
function swimInWater(grid) {
// Union-Find: add cells in increasing elevation until (0,0) and (n-1,n-1) connect.
const n = grid.length, N = n * n, pos = new Array(N);
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) pos[grid[r][c]] = [r, c];
const parent = [...Array(N).keys()], on = new Array(N).fill(false);
const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
for (let t = 0; t < N; t++) {
const [r, c] = pos[t]; on[r * n + c] = true;
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr >= 0 && nc >= 0 && nr < n && nc < n && on[nr * n + nc]) parent[find(r * n + c)] = find(nr * n + nc);
}
if (on[0] && on[N - 1] && find(0) === find(N - 1)) return t;
}
return N - 1;
}