Skip to content
QuizMaker logoQuizMaker
Activity
DSA Interview Patterns Roadmap

No lessons available

CONTENTS

Grid BFS: Multi-source Distance Problems

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

DSA Interview Patterns Roadmap
Graphs BFS and DFS
dsa
coding interview
+5
May 29, 2026
21
A

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

  • Rotting Oranges
  • 01 Matrix
  • As Far from Land as Possible
  • Shortest Bridge
  • Find the Safest Path in a Grid

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

  • No source cells
  • No target cells
  • Boundary cells
  • Marking after pop creates duplicates

Common Mistakes

  • Running BFS from each source separately
  • Using DFS for shortest unweighted distance
  • Incrementing time after an empty final layer

Complexity

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

Java, C++ and Python Notes

  • Java: prefer explicit classes and clear helper methods over clever one-liners.
  • C++: use vector, unordered_map, set, priority_queue, and long long when sums can grow.
  • Python: keep state readable with dict, set, deque, heapq, and lru_cache where appropriate.

Quick Revision Checklist

  • Name the pattern before coding.
  • State the invariant or DP state in one sentence.
  • Dry-run the smallest non-trivial example.
  • Close with time and space complexity.

Share this article

Test your knowledge

Take a quick quiz based on this chapter.

mediumDSA Interview Patterns
Quiz: Grid BFS: Multi-source Distance Problems
6 questions10 min

0 comments

Please login to comment.
No comments yet.
Lesson 1 of 7 in Graphs BFS and DFS
Next in Graphs BFS and DFS
Graph Traversal, Cycle Detection and Topological Sort
Back to DSA Interview Patterns Roadmap
Back to moduleCategories