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
Seed the queue with every already-rotten cell at minute 0, so all sources spread in lockstep and each popped cell carries the minute it rots. A visited set keeps the first (and therefore earliest) arrival at each cell and drops the rest. maxi tracks the last minute reached, and good_count counts fresh oranges still standing, so a non-zero count at the end means some orange was unreachable.
- Time
- O(2×m×n)
getRottenIndicesis a full grid scan to seed the queue and count fresh oranges - oneO(m×n)pass.- The BFS loop then processes every cell (each enqueued a bounded number of times but touched once through the
visitedguard) - a secondO(m×n)pass. - Space
- O(2×m×n)
queueholds up to every cell in the worst case -O(m×n).visitedalso holds up to every cell - anotherO(m×n).
542. 01 Matrix
54201 Matrix
Seed the queue with every 0 cell at distance 0, so all sources spread in lockstep and each popped cell carries the distance it was reached at. res starts filled with the worst-case distance n*m and is lowered to the first (and therefore shortest) distance each cell is popped with. A visited set stops a cell from being expanded twice.
- Time
- O(m×n)
- Each cell is enqueued once per zero-distance neighbour (at most 4 times) and processed once, so the work is linear in the number of cells.
- Space
- O(m×n)
- The queue, the
visitedset, and theresmatrix all hold up to every cell.
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
neighbors yields all 8 surrounding cells (orthogonal and diagonal). The queue starts at (0, 0, 1), and each popped cell that hasn't been visited enqueues its open (0) neighbours at distance + 1. Because BFS explores in layers, the first time (n-1, n-1) is popped it carries the shortest distance.
- Time
- O(n²)
- Each of the n² cells is visited once and expands to at most 8 neighbours.
- Space
- O(n²)
- The queue and the
visitedset both hold up to every cell.