The edge case about passing through the destination at the same minute fire arrives tripped me up for a bit.
Model the problem as a time-expanded graph where each cell has a fire arrival time. Use multi-source BFS from all initial fire cells to compute the earliest time fire reaches each cell, then binary search on the waiting time W to check if a path exists from start to goal where you arrive at each cell before the fire. The check uses BFS on the grid with the constraint that your arrival time at a cell must be strictly less than the fire arrival time.
Pro tip: Clarify edge cases upfront: if the start or goal is initially on fire, return -1; if the goal is unreachable by fire (e.g., surrounded by walls), return 10^9. Also, mention that you can wait at the start only, not en route, which simplifies the problem.
Run multi-source BFS from all initially burning cells to compute the earliest time each cell catches fire. Use a 2D array fireTime initialized to infinity, and update with BFS level order.
For a given waiting time W, determine if there exists a path from start to goal such that you arrive at each cell strictly before the fire. Use BFS where you can only move to cells where your arrival time < fireTime[cell].
Binary search W in the range [0, maxPossibleTime]. The maximum possible time is bounded by the maximum fireTime or grid size. If W=0 is infeasible, return -1. If W can be arbitrarily large (goal never catches fire), return 10^9.
Check if start or goal is initially on fire: if so, return -1. If goal is unreachable by fire (fireTime[goal] = infinity), return 10^9. Also, if start equals goal, return 10^9 if not on fire, else -1.
The fire BFS is O(R*C). Each feasibility check is O(R*C). Binary search adds a log factor, so overall O(R*C log(R*C)). Mention that you can also use a single BFS with time as a dimension, but binary search is simpler.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.