Skip to interview prep
Apexed

What is multi-source BFS, and how does flood fill relate to it?

MediumGraph algorithms

Technical

Content review

Report an error

Not yet reviewed

Type or dictate your answer. Your draft is saved on this device.

Show model answer

Multi-source BFS starts with all sources in the queue at distance 0, which computes each vertex's distance to its nearest source in one O(V + E) pass, equivalent to adding a virtual super-source. Classic uses: distance of every cell to the nearest gate, rotting oranges (minutes until all are rotten), or nearest hospital for every town.

Flood fill is a single-source BFS or DFS on an implicit grid graph: start from a cell and visit all 4- (or 8-) connected neighbors that share its color, recoloring or counting them. It is O(rows·cols) time and space; counting islands is repeated flood fill from every unvisited land cell.

Example program

What is multi-source BFS, and how does flood fill relate to it — Data structures & algorithms interview question — Apexed