Swim in Rising Water
Master this topic with zero to advance depth.
Swim in Rising Water
On an grid, elevation at (i, j) is grid[i][j]. Return the least time such that you can swim from top-left to bottom-right.
Examples
Level I: Dijkstra (Min-Max Path)
Intuition
This is a variant of shortest path where the 'cost' of a path is elevations on path. Dijkstra's algorithm with a min-priority queue works perfectly.
Detailed Dry Run
grid = [[0,2],[1,3]].
- Start (0,0) elev 0.
- Neighbors: (0,1) cost 2, (1,0) cost 1.
- Smallest max: (1,0) cost 1.
- Neighbor of (1,0) is (1,1) cost 3.
- Result: 3.
Level II: Optimal (Union Find / Kruskal's)
Intuition
Treat the grid as a graph where each edge has a weight equal to the maximum elevation of its two endpoints. Sort all possible edge weights (or cell elevations). Add cells one by one in increasing order of elevation and connect them with their visited neighbors. The first time the top-left and bottom-right are in the same component, the current elevation is the answer.
Detailed Dry Run
grid = [[0,2],[1,3]].
- Cells sorted by elevation: (0,0):0, (1,0):1, (0,1):2, (1,1):3.
- Add (0,0). Add (1,0), connect to (0,0).
- Add (0,1), connect to (0,0).
- Add (1,1), connect to (1,0) and (0,1).
- (0,0) and (1,1) are connected. Result: 3.
Level III: Optimal (Binary Search + DFS/BFS)
Intuition
The answer lies in . For a fixed , we check if a path exists using only squares with elevation using BFS/DFS.
Detailed Dry Run
grid = [[0,2],[1,3]]. BS on range [0, 3]. Try T=2: Path (0,0)->(1,0) works, but (1,0) neighbors are (1,1) elev 3 > 2. Fails. Try T=3: Path (0,0)->(1,0)->(1,1) works! Possible. Result: 3.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.