[LeetCode] Minimum Time Takes to Reach Destination Without Drowning

2814. Minimum Time Takes to Reach Destination Without Drowning

You are given an n * m 0-indexed grid of string land. Right now, you are standing at the cell that contains "S", and you want to get to the cell containing "D". There are three other types of cells in this land:

  • ".": These cells are empty.
  • "X": These cells are stone.
  • "*": These cells are flooded.

At each second, you can move to a cell that shares a side with your current cell (if it exists). Also, at each second, every empty cell that shares a side with a flooded cell becomes flooded as well.
There are two problems ahead of your journey:

  • You can’t step on stone cells.
  • You can’t step on flooded cells since you will drown (also, you can’t step on a cell that will be flooded at the same time as you step on it).

Return the minimum time it takes you to reach the destination in seconds, or -1 if it is impossible.

Note that the destination will never be flooded.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
int minimumSeconds(vector<vector<string>>& land) {
int n = land.size(), m = land[0].size();
queue<pair<int,int>> at;
queue<pair<int,int>> water;
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
if(land[i][j] == "*") water.push({i,j});
if(land[i][j] == "S") at.push({i,j});
}
int res = 0;
auto inc = [&](int y, int x) {return 0 <= y and y < n and 0 <= x and x < m;};
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
while(at.size()) {
int wsz = water.size();
while(wsz--) {
auto [y,x] = water.front(); water.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(inc(ny,nx) and land[ny][nx] != "*" and land[ny][nx] != "D" and land[ny][nx] != "X") {
if(land[ny][nx] == "D") return -1;
land[ny][nx] = "*";
water.push({ny,nx});
}
}
}
int asz = at.size();
while(asz--) {
auto [y,x] = at.front(); at.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(inc(ny,nx) and (land[ny][nx] == "." or land[ny][nx] == "D")) {
if(land[ny][nx] == "D") return res + 1;
land[ny][nx] = "S";
at.push({ny,nx});
}
}
}
res += 1;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/11/PS/LeetCode/minimum-time-takes-to-reach-destination-without-drowning/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.