Technique
Multi-source BFS
Seed the BFS queue with all sources at distance 0 so one pass gives every cell's distance to its nearest source.
Learn firstGraph BFS / DFS
0%
mastery
0/9 solved
0/9 solved
Recognise it
The signal
distance to nearest X for every cell
1Brute force
BFS from each source separately: O(k * V).
2The observation
Per-source BFS: a virtual super-source joins them in one search.
3Why it works
Cells are dequeued in non-decreasing distance to the nearest source.
Reach for it when
- +spreading processes (rotting, fire)
- +boundary-first reverse search
Not when
- ×weighted spread (multi-source dijkstra)
- ×need the distance to a specific source
Practice
0/9 solved
- MonstersCSESMedium
- Rotting OrangesAmazon, UberMedium
- 01 MatrixGoogle, UberMedium
- Walls and GatesPremiumMedium
- Rotting OrangesIntuitOAMedium
- Paths Avoiding Breach RadiusD. E. ShawOAMedium
- Pacific Atlantic Water FlowGoogle, AmazonMedium
- Nearest Opposite ParityCodeforces1900
- Nearest ShopsCSESHard
Pitfalls
Misconceptions
- !simulating minute by minute with full grid rescans
Go deeper1 combinations · resources
Combinations
Multi-source BFS+Graph BFS / DFS
escape before the fire/monsters reach a cell
- Multi-source BFS:
- computes earliest arrival of monsters/fire
- Graph BFS / DFS:
- BFS for the player constrained by those times