10. Swim in Rising Water
You are given an $n \times n$ integer matrix grid where each cell represents the elevation at that point. Rain starts falling and time $t$ increases. You can swim between adjacent cells if elevation at both cells is at most $t$. Return the least time until you can reach (n-1, n-1).
How It Works & Algorithmic Design
Solves using Modified Dijkstra's Algorithm:
- Min-Heap Priority Queue: Store
(maxElevationOnPath, r, c). - Initialization: Push
(grid[0][0], 0, 0)to heap. Markgrid[0][0]visited. - Dijkstra Loop:
- Pop element
(t, r, c)with smallest path elevation. - If
r === n-1 && c === n-1, returntinstantly. - For each unvisited neighbor
(nr, nc):newTime = Math.max(t, grid[nr][nc]).- Push
(newTime, nr, nc)into heap.
- Pop element
Why This Approach Works Best
Greedily picks paths minimizing maximum water height in $O(n^2 \log n)$ time.
Example Walkthrough
[[0,2],[1,3]]
2x2 grid.
(0,0) [h=0] -> (1,0) [h=1] -> (1,1) [h=3]
Max height on path is 3.
3
Minimum swim time.
Answer: Swim in Rising Water Dijkstra implementation
function swimInWater(grid) {
const n = grid.length;
const visited = Array.from({ length: n }, () => new Array(n).fill(false));
const heap = [[grid[0][0], 0, 0]]; // Simulated Min-Heap
visited[0][0] = true;
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
while (heap.length) {
heap.sort((a, b) => a[0] - b[0]);
const [t, r, c] = heap.shift();
if (r === n - 1 && c === n - 1) return t;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < n && nc < n && !visited[nr][nc]) {
visited[nr][nc] = true;
heap.push([Math.max(t, grid[nr][nc]), nr, nc]);
}
}
}
return 0;
}Find path minimizing maximum cell elevation using priority queue traversal.
Path cost is determined by max single elevation encountered.
Dijkstra expands search along globally lowest required water levels.
Time complexity $O(n^2 \log n)$.