[LeetCode] Swim in Rising Water

778. 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).

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).

  • heap solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
vector<vector<int>> vis(n, vector<int>(m, -1));
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> q;
q.push({grid[0][0], 0,0});
vis[0][0] = grid[0][0];
while(!q.empty()) {
auto [cost, y, x] = q.top(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and (vis[ny][nx] == -1 or vis[ny][nx] > max(grid[ny][nx], vis[y][x]))) {
vis[ny][nx] = max(grid[ny][nx], vis[y][x]);
if(ny == n - 1 and nx == m - 1) return vis[ny][nx];
q.push({vis[ny][nx], ny, nx});
}
}
}
return vis[n-1][m-1];
}
};
  • queue solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
vector<vector<int>> vis(n, vector<int>(m, -1));

queue<pair<int, int>> q;
q.push({0,0});
vis[0][0] = grid[0][0];

while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and (vis[ny][nx] == -1 or vis[ny][nx] > max(grid[ny][nx], vis[y][x]))) {
vis[ny][nx] = max(grid[ny][nx], vis[y][x]);
q.push({ny, nx});
}
}
}
return vis[n-1][m-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/09/PS/LeetCode/swim-in-rising-water/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.