778. Swim in Rising Water
Problem
grid[i][j] is the elevation of a cell in an n×n grid (all values distinct, 0…n² − 1). At time t the water everywhere is t deep, and you can swim between adjacent cells (up, down, left, right) instantly if both elevations are at most t. Starting at the top-left, return the least time at which you can reach the bottom-right.
Example: [[0,2],[1,3]] → 3
Constraints: n ≤ 50.
Cost of a path = the max cell on it. Dijkstra where the "distance" is max(current, grid[next]): always expand the lowest-elevation frontier cell.
Complexity: O(n² log n).
class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
pq, seen = [(grid[0][0], 0, 0)], {(0, 0)}
while pq:
t, r, c = heappop(pq)
if r == 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))
heappush(pq, (max(t, grid[nr][nc]), nr, nc))
assert Solution().swimInWater([[0, 2], [1, 3]]) == 3
G = [[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]]
assert Solution().swimInWater(G) == 16
class Solution {
public int swimInWater(int[][] grid) {
int n = grid.length;
boolean[][] seen = new boolean[n][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {time, r, c}
pq.add(new int[]{grid[0][0], 0, 0});
seen[0][0] = true;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (true) {
int[] cur = pq.poll();
if (cur[1] == n - 1 && cur[2] == n - 1) return cur[0];
for (int[] d : dirs) {
int nr = cur[1] + d[0], nc = cur[2] + d[1];
if (nr >= 0 && nc >= 0 && nr < n && nc < n && !seen[nr][nc]) {
seen[nr][nc] = true;
pq.add(new int[]{Math.max(cur[0], grid[nr][nc]), nr, nc});
}
}
}
}
}
type cellHeap [][3]int // (time, row, col), smallest time first
func (h cellHeap) Len() int { return len(h) }
func (h cellHeap) Less(i, j int) bool { return h[i][0] < h[j][0] }
func (h cellHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *cellHeap) Push(x any) { *h = append(*h, x.([3]int)) }
func (h *cellHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func swimInWater(grid [][]int) int {
n := len(grid)
seen := make([][]bool, n)
for i := range seen {
seen[i] = make([]bool, n)
}
seen[0][0] = true
pq := &cellHeap{{grid[0][0], 0, 0}}
dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
for pq.Len() > 0 {
cur := heap.Pop(pq).([3]int)
t, r, c := cur[0], cur[1], cur[2]
if r == n-1 && c == n-1 {
return t
}
for _, d := range dirs {
nr, nc := r+d[0], c+d[1]
if nr >= 0 && nr < n && nc >= 0 && nc < n && !seen[nr][nc] {
seen[nr][nc] = true
heap.Push(pq, [3]int{max(t, grid[nr][nc]), nr, nc})
}
}
}
return -1
}