Swim in Rising Water
Master this topic with zero to advance depth.
Swim in Rising Water
You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
At time t, the water level everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares are at most t. You can swim infinite distances in zero time. You start at the top left square (0, 0) at time 0.
Return the least time until you can reach the bottom right square (n - 1, n - 1).
Visual Representation
Grid:
0 1 2
3 4 5
6 7 8
You start at 0. You need time 8 to reach 8 because the bottom-right corner itself is 8.
At t=8, all cells are <= 8, so a path exists.
Result: 8Examples
At time 3, we can swim along the path 0-1-3.
Level II: Intermediate (Binary Search on Answer + BFS)
Intuition
Since the possible time answers range from 0 to , we can binary search for the minimum time such that there is a path from to using only cells with elevation .
Thought Process
- Search range
low = 0, high = N*N - 1. - For each
mid(candidate time):- Run a BFS/DFS from
(0,0). - Only move to neighbors with
grid[nr][nc] <= mid. - If
(N-1, N-1)is reachable,midis possible; try lower. - Otherwise,
midis impossible; try higher.
- Run a BFS/DFS from
Why it's Level II
It's very robust and often easier to come up with than the Dijkstra/heap-based approach.
Detailed Dry Run
3x3, grid[0][0]=3, grid[2][2]=5
- high=8, low=0. mid=4. Can we reach 2,2? Start (0,0) is 3. OK. BFS explores neighbors <= 4. If path exists, high=4.
- mid=2. grid[0][0]=3 > 2. Impossible. low=3.
- Continue binary search.
Level III: Optimal (Dijkstra's Algorithm)
Intuition
This is a pathfinding problem where the weight of a path is the maximum elevation on that path. We want to find the path with the minimum such weight. This is a variant of Dijkstra where the 'distance' is the max-so-far elevation.
Thought Process
- Use a Min-Heap/Priority Queue to store
(max_elevation_so_far, r, c). - Start with
(grid[0][0], 0, 0). - Keep a
visitedset to avoid cycles. - In each step:
- Pop
(t, r, c). Thistis the minimum time needed to reach this cell. - If
(r, c)is(n-1, n-1), returnt. - For each 4-directional neighbor
(nr, nc):- The time needed to reach neighbor is
max(t, grid[nr][nc]). - If unvisited, push to queue.
- The time needed to reach neighbor is
- Pop
Pattern: Min-Max Path (Dijkstra)
Detailed Dry Run
Grid: [[0,2],[1,3]]
- PQ: [(0, 0, 0)]
- Pop (0,0,0). Neighbors: (0,1): max(0,2)=2, (1,0): max(0,1)=1.
- PQ: [(1, 1, 0), (2, 0, 1)]
- Pop (1,1,0). Neighbors: (1,1): max(1,3)=3.
- PQ: [(2, 0, 1), (3, 1, 1)]
- Pop (2,0,1). Neighbors: (1,1): max(2,3)=3. (Already in PQ with 3, no update).
- Pop (3,1,1). Reached (1,1). Return 3. Result: 3
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.