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
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen