Minimum Time Takes to Reach Destination Without Drowning - Problem
You find yourself trapped on a dangerous island represented by an n ร m grid. Your mission is to escape from your starting position 'S' to the safe destination 'D' before the rising flood waters consume the entire island!
The island contains:
'.'- Empty cells you can walk through'X'- Stone obstacles that block your path'*'- Flooded areas that spread each second'S'- Your starting position'D'- The safe destination (never floods)
Movement Rules:
- Each second, you can move to an adjacent cell (up, down, left, right)
- Each second, after your move, floods spread to all empty cells adjacent to flooded areas
- You cannot step on stones or flooded cells
- You cannot step on a cell that will be flooded at the same time you arrive
Return the minimum time in seconds to reach the destination, or -1 if escape is impossible.
Input & Output
example_1.py โ Basic Grid
$
Input:
grid = [['S','.','.','.','D'],['.','X','X','X','.'],['.','.','.','.','.'],['.','*','.','.','.'],['.','.','.','.','.']]
โบ
Output:
6
๐ก Note:
One possible path: S โ down โ down โ right โ right โ up โ up โ right โ D. The flood spreads from (3,1) but we can navigate around it to reach D safely in 6 seconds.
example_2.py โ Impossible Case
$
Input:
grid = [['S','X','*'],['D','X','.'],['.','.','.']]
โบ
Output:
-1
๐ก Note:
The flood at (0,2) will spread and block all possible paths to reach D from S. The stone barrier at X also limits movement options, making escape impossible.
example_3.py โ Quick Escape
$
Input:
grid = [['S','.','D'],['.','.','.'],['*','.','.']]
โบ
Output:
2
๐ก Note:
The shortest path is S โ right โ right โ D, taking exactly 2 seconds. The flood starts at (2,0) but won't reach our path in time to block it.
Constraints
- 1 โค n, m โค 1000
- Grid contains exactly one 'S' and one 'D'
- Grid may contain 0 or more '*' (flood sources)
- Grid cells are one of: '.', 'X', 'S', 'D', '*'
- Destination 'D' will never be flooded
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code