Problem Description
You are given an n x m grid where each cell represents a type of terrain. The grid contains:
- "S": the starting cell
- "D": the destination cell (which will never be flooded)
- ".": an empty cell where you can move
- "X": a stone cell that cannot be stepped on
- "*": a flooded cell
Each second, you can move to one of the four adjacent cells (up, down, left, right) provided that the cell is not a stone or flooded. In the same second, the water floods any empty cell adjacent to a flooded cell. Note that you cannot move onto a cell that is flooded or will be flooded in that same second.
Return the minimum number of seconds required to reach the destination "D" from "S". If it is impossible, return -1.
Key Insights
- Use a multi-step Breadth-First Search (BFS) approach.
- First, simulate the flood spread: perform a multi-source BFS starting from all initially flooded cells to compute the time each empty cell gets flooded.
- Then, perform a BFS from the starting cell "S", ensuring that you only move into cells that are not currently flooded or will be flooded at the time of arrival (i.e., arrival time must be strictly less than the flood time for that cell).
- Carefully handle boundaries and obstacles ("X" cells) to avoid invalid moves.
Space and Time Complexity
Time Complexity: O(nm) — each cell is processed a constant number of times in both flood and path BFS. Space Complexity: O(nm) — additional space for the flood time grid and BFS queue.
Solution
We use two BFS traversals:
- Flood Spread BFS: Start from all cells initially marked "*" and compute the earliest time each empty cell (".") can get flooded. The resulting "flood_time" matrix helps decide if a cell is safe to move into at a given time during the path search.
- Path BFS: Starting from "S", we explore all possible moves, making sure that when moving to a cell at time t+1, that cell’s flood time is either not set (meaning it will not flood) or t+1 is strictly less than the flood time. This ensures the safe arrival.
This combined approach ensures that we are always aware of both the flood spread dynamics and the allowed moves for the person.