BFS
Breadth-first search on a grid expands in layers: every cell at distance d is
processed before any cell at distance d + 1. That layering is what makes BFS
the tool for shortest-path and elapsed-time questions, where DFS answers
"reachable?" but not "how far?" - see
Grids as Graphs and
why BFS's first arrival is shortest.
Multi-Source BFS
Seed the queue with every starting cell at distance 0 rather than running one
BFS per source, and the layers measure distance to the nearest source. The
last layer popped is the answer.
994. Rotting Oranges
Medium·
3 Approaches
BFS
O(2*m*n)O(2*m*n)
BFS without visited
O(2*m*n)O(m*n)
BFS with O(1) space
O(m*n + (m*n)²)O(1)
FIG. 994 ROTTING ORANGES BFS● INTERACTIVE
visualization loads as you reach it
542. 01 Matrix
Medium·
54201 Matrix
Multi-Source BFS
O(m*n)O(2mn)
FIG. 542 01 MATRIX BFS● INTERACTIVE
visualization loads as you reach it
Single-Source BFS
From one cell, the same layering answers "shortest distance from here to
there?" - and nothing stops a layer spreading in 8 directions instead of 4, as
long as neighbours yields them all.
1091. Shortest Path in Binary Matrix
Medium·
2 Approaches
BFS with Visited Set
O(n²)O(2n^2)
BFS with Grid as Visited (In-Place)
O(n²)O(n²)
FIG. 1091 SHORTEST PATH BINARY MATRIX BFS● INTERACTIVE
visualization loads as you reach it