Grid BFS: Multi-source Distance Problems | DSA Interview Patterns - Study Chapter | QuizMaker

Solve grid distance and spread problems by starting BFS from all sources at once.

Read
18m
Type
Chapter
Access
Free

Course

DSA Interview Patterns Roadmap

Topic

Graphs BFS and DFS

Learning Outcome

Solve grid distance and spread problems by starting BFS from all sources at once.

Pattern Recognition

ItemDetail
Core signalMany cells spread simultaneously or every cell needs distance to the nearest source.
Use whenMovement is unweighted and shortest distance/time is needed.
Avoid whenThe required invariant is not monotonic or the input constraints point to a simpler direct scan.

Intuition

A multi-source BFS is the same as adding a virtual source connected to every starting cell.

Exact Practice Question Names

Interview Approach

  1. Push all source cells before BFS starts.
  2. Mark visited when enqueuing.
  3. Process by levels for time or distance.
  4. For two-phase problems, first compute scores, then search on those scores.

Pseudocode

queue = all source cells
mark sources
steps = 0
while queue not empty:
  for each cell in current level:
    for each neighbor:
      if valid and unvisited: mark and push
  steps += 1

Sample Dry Run

In rotten oranges, all rotten cells start at minute 0. Every BFS layer rots adjacent fresh oranges together, giving minimum time.

Edge Cases

Common Mistakes

Complexity

ItemDetail
Expected timeO(mn).
Expected spaceO(mn) worst case queue/visited.

Java, C++ and Python Notes

Quick Revision Checklist

Tags

Open on QuizMaker