Minimum Time Takes to Reach Destination Without Drowning - Problem
You are given an n * m 0-indexed grid of strings called 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.
Input & Output
Example 1 — Basic Escape Path
$
Input:
land = [["S",".","D"],[".","X","."],[".","*","."]]
›
Output:
3
💡 Note:
Start at S, move right to (0,1), then down to (1,2), then up to (0,2) to reach D. Takes 3 seconds total, avoiding the flood spreading from * and the stone X.
Example 2 — No Escape Possible
$
Input:
land = [["S","*"],["*","D"]]
›
Output:
-1
💡 Note:
The starting position S is immediately surrounded by flood sources *. There's no safe path to reach destination D.
Example 3 — Direct Path Available
$
Input:
land = [["S",".","D"],[".",".","."],["*",".","."]]
›
Output:
2
💡 Note:
Simple path: S → right to (0,1) → right to (0,2) reaching D. Takes 2 seconds, faster than the flood can reach the path.
Constraints
- 1 ≤ n, m ≤ 300
- land[i][j] ∈ {"S", "D", ".", "X", "*"}
- There is exactly one "S" and one "D"
- The destination "D" will never be flooded
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code