Graph / BFS•Pattern: Multi-Source BFS•Medium

Walls and gates — fill distance to nearest gate

Problem Intuition & Objective

Fill each empty room with the distance to its nearest gate using multi-source BFS.

Time ComplexityO(m×n)
Optimal
Space ComplexityO(m×n)
Memory Bounds
Optimal Algorithmic Approach

Multi-source BFS from all gates at once.

Core Invariants & Edge Cases

  • Start BFS from all gates (value 0) simultaneously
  • The first time a cell is reached is its shortest distance
  • Walls (value -1) block propagation
Previous ProblemRotting oranges — minimum time for all to rot (BFS)Next Problem Group anagrams together

System Design & Architecture Roadmap

Coding interviews are only 50% of the bar. Master High-Level Design, distributed systems, and Object-Oriented LLD.