Minimum Time Takes to Reach Destination Without Drowning

BFS with a time-dependent flood wavefront preventing entry into recently flooded cells.

Hard
Time O(m*n) Space O(m*n)
LeetCode
10 min read
bfs multi-source-bfs grid

Problem#

A grid contains S (start), D (destination), . (land), * (water source), and X (blocked). Water spreads to adjacent land cells every minute. You move one step per minute. You can’t step into a flooded cell. Return the minimum time to reach D, or -1.

Examples#

  • grid = [["D",".","*"],[".",".","."],[".","S","."]]3
  • grid = [["D","X","*"],[".",".","."],[".",".","S"]]-1

Constraints#

  • 2 <= m, n <= 100. There is exactly one S and one D.

Approach#

Multi-source BFS from all water cells to compute the earliest flood time per cell. Then BFS from S: at step t+1, only enter a neighbor if its flood time is strictly greater than t+1 (or it’s D).

Solution#

Minimum Time Takes to Reach Destination Without Drowning
class Solution {
public:
int minimumSeconds(vector<vector<string>>& land) {
int m = land.size(), n = land[0].size();
const int INF = INT_MAX;
vector<vector<int>> flood(m, vector<int>(n, INF));
queue<pair<int,int>> q;
int sr = 0, sc = 0, dr = 0, dc = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (land[i][j] == "*") { flood[i][j] = 0; q.push({i, j}); }
else if (land[i][j] == "S") { sr = i; sc = j; }
else if (land[i][j] == "D") { dr = i; dc = j; }
}
}
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (int k = 0; k < 4; ++k) {
int nr = r + dx[k], nc = c + dy[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
if (land[nr][nc] == "X" || land[nr][nc] == "D") continue;
if (flood[nr][nc] != INF) continue;
flood[nr][nc] = flood[r][c] + 1;
q.push({nr, nc});
}
}
vector<vector<int>> dist(m, vector<int>(n, -1));
dist[sr][sc] = 0;
queue<pair<int,int>> p;
p.push({sr, sc});
while (!p.empty()) {
auto [r, c] = p.front(); p.pop();
int t = dist[r][c];
for (int k = 0; k < 4; ++k) {
int nr = r + dx[k], nc = c + dy[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
if (land[nr][nc] == "X") continue;
if (dist[nr][nc] != -1) continue;
int nt = t + 1;
if (land[nr][nc] == "D") return nt;
if (nt < flood[nr][nc]) {
dist[nr][nc] = nt;
p.push({nr, nc});
}
}
}
return -1;
}
};

Editorial#

Decoupling water spread (a static BFS that respects walls and treats D as un-floodable per problem variant) from player movement makes the second BFS a simple shortest-path with a per-cell forbidden timestamp. The strict inequality nt < flood[nr][nc] enforces “arrive before water does”.

Complexity#

  • Time: O(m*n).
  • Space: O(m*n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.