You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the least time until you can reach the bottom right square(n - 1, n - 1)if you start at the top left square(0, 0).
Input:
grid = [[0,2],[1,3]]
Output:
3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.
You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.
Input:
grid =[[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]]Output:
16Explanation: The final route is shown.We need to wait until time 16 so that(0,0) and (4,4) are connected.
We want to reach the bottom-right cell as soon as possible, but we can only move to a cell if the water level (time) is at least as high as the highest elevation we’ve seen so far on our path. Dijkstra’s algorithm is ideal for finding the minimum ‘maximum elevation’ path in a weighted grid.
classSolution {
public:int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<bool>> vis(n, vector<bool>(n, false));
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
pq.push({grid[0][0], 0, 0});
vector<int> dx{0,0,1,-1}, dy{1,-1,0,0};
while (!pq.empty()) {
auto [t, x, y] = pq.top(); pq.pop();
if (x == n-1&& y == n-1) return t;
if (vis[x][y]) continue;
vis[x][y] = true;
for (int d =0; d <4; ++d) {
int nx = x + dx[d], ny = y + dy[d];
if (nx >=0&& nx < n && ny >=0&& ny < n &&!vis[nx][ny]) {
pq.push({max(t, grid[nx][ny]), nx, ny});
}
}
}
return-1;
}
};
classSolution {
publicintswimInWater(int[][] grid) {
int n = grid.length;
boolean[][] vis =newboolean[n][n];
PriorityQueue<int[]> pq =new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
pq.offer(newint[]{grid[0][0], 0, 0});
int[] dx = {0,0,1,-1}, dy = {1,-1,0,0};
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int t = cur[0], x = cur[1], y = cur[2];
if (x == n-1 && y == n-1) return t;
if (vis[x][y]) continue;
vis[x][y]=true;
for (int d = 0; d < 4; d++) {
int nx = x + dx[d], ny = y + dy[d];
if (nx >= 0 && nx < n && ny >= 0 && ny < n &&!vis[nx][ny]) {
pq.offer(newint[]{Math.max(t, grid[nx][ny]), nx, ny});
}
}
}
return-1;
}
}
classSolution {
funswimInWater(grid: Array<IntArray>): Int {
val n = grid.size
val vis = Array(n) { BooleanArray(n) }
val pq = java.util.PriorityQueue(compareBy<Triple<Int,Int,Int>> { it.first })
pq.add(Triple(grid[0][0], 0, 0))
val dx = intArrayOf(0,0,1,-1)
val dy = intArrayOf(1,-1,0,0)
while (pq.isNotEmpty()) {
val(t, x, y) = pq.poll()
if (x == n-1&& y == n-1) return t
if (vis[x][y]) continue vis[x][y] = truefor (d in0..3) {
val nx = x + dx[d]
val ny = y + dy[d]
if (nx in0 until n && ny in0 until n && !vis[nx][ny]) {
pq.add(Triple(maxOf(t, grid[nx][ny]), nx, ny))
}
}
}
return -1 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defswimInWater(self, grid: list[list[int]]) -> int:
n = len(grid)
vis = [[False]*n for _ in range(n)]
import heapq
pq = [(grid[0][0], 0, 0)]
dx = [0,0,1,-1]
dy = [1,-1,0,0]
while pq:
t, x, y = heapq.heappop(pq)
if x == n-1and y == n-1:
return t
if vis[x][y]: continue vis[x][y] =Truefor d in range(4):
nx, ny = x+dx[d], y+dy[d]
if0<= nx < n and0<= ny < n andnot vis[nx][ny]:
heapq.heappush(pq, (max(t, grid[nx][ny]), nx, ny))
return-1
use std::collections::BinaryHeap;
use std::cmp::Reverse;
impl Solution {
pubfnswim_in_water(grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
letmut vis =vec![vec![false; n]; n];
letmut pq = BinaryHeap::new();
pq.push(Reverse((grid[0][0], 0, 0)));
let dx = [0,0,1,-1];
let dy = [1,-1,0,0];
whilelet Some(Reverse((t, x, y))) = pq.pop() {
if x == n-1&& y == n-1 { return t; }
if vis[x][y] { continue; }
vis[x][y] =true;
for d in0..4 {
let nx = x asi32+ dx[d];
let ny = y asi32+ dy[d];
if nx >=0&& nx < n asi32&& ny >=0&& ny < n asi32 {
let nx = nx asusize; let ny = ny asusize;
if!vis[nx][ny] {
pq.push(Reverse((t.max(grid[nx][ny]), nx, ny)));
}
}
}
}
-1 }
}