762. Minimum Time Takes to Reach Destination Without Drowning
You are given a 0-indexed grid land with dimensions n x m, where each cell is a string representing a type of terrain. You begin at the cell marked "S" (start) and your goal is to reach the cell marked "D" (destination).
The grid contains the following types of cells:
- "S": Your starting cell.
- "D": Your destination. This cell will never be flooded.
- ".": An empty cell.
- "X": A stone cell that you cannot step on.
- "*": A flooded cell that you cannot step on.
Each second, you can move to any adjacent cell (up, down, left, or right) that exists within the grid. Simultaneously, every empty cell (".") that is adjacent (shares a side) to a flooded cell ("*" ) becomes flooded at the same time.
There are two constraints during your journey:
- You cannot move onto stone cells ("X").
- You cannot move onto flooded cells ("*"), nor can you move into a cell at the same time it is about to be flooded.
Return the minimum number of seconds required to reach the destination "D" from the starting cell "S". If it is impossible to reach the destination safely, return -1.
Example 1:
Input : land = [["S", ".", "D"], [".", ".", "."], [".", "*", "."]]
Output :Â 2
Explanation:
At time t = 0, you start at "S" (cell [0,0]) while the flooded cell is at [2,1]. At t = 1, the water spreads from [2,1] to its adjacent empty cells, and you move to cell [0,1]. At t = 2, you move from [0,1] to "D" (cell [0,2]), reaching the destination just before any water would affect your path.
Example 2:
Input : land = [["D", "X", "*"], [".", ".", "."], [".", ".", "S"]]
Output : -1
Explanation :
Here, "S" is at [2,2] and "D" is at [0,0]. Although there is a possible route in terms of distance, the spread of water from the flooded cell at [0,2] blocks all safe paths to "D", making it impossible to reach the destination without drowning.
Now Your Turn!
Pick the correct output for the given inputInput : land = [["S", ".", "."], [".", ".", "."], [".", ".", "D"], ["*", ".", "."]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 2 ≤ n, m ≤ 100
- land consists only of "S", "D", ".", "*", and "X".
- There is exactly one "S" cell and exactly one "D" cell in the grid.