LeetCode ยท BFS

BFS Problem Set

Level-order traversal, shortest path in unweighted graphs, multi-source expansion, and state-space search. If the prompt asks for the minimum number of steps, nearest distance, or simultaneous spread, BFS should be one of your first candidates.

Related pages: BFS ยท Graph Basics ยท Graphs
DifficultyPatternProblemKey Insight
Mediumflood-fillLC 200 ยท Number of IslandsTreat each land cell as a node and flood one connected component at a time. BFS marks an entire island from each unvisited start cell.
Mediummulti-sourceLC 994 ยท Rotting OrangesEnqueue every rotten orange first. One BFS layer equals one minute of spread, so the number of layers gives the answer directly.
Mediummulti-sourceLC 542 ยท 01 MatrixReverse the search: start from all zero cells and expand outward. The first time BFS reaches a one-cell is its nearest-zero distance.
Mediumgrid shortest-pathLC 1091 ยท Shortest Path in Binary MatrixStandard shortest-path BFS on an unweighted grid, but with 8 directions. Distance is the BFS level when you first reach the bottom-right cell.
Hardimplicit graphLC 127 ยท Word LadderEach word is a node; edges connect words differing by one character. BFS finds the shortest transformation sequence in this implicit graph.
Hardstate-spaceLC 773 ยท Sliding PuzzleEach board arrangement is a node and each legal swap is an edge. Encode states compactly and use BFS to guarantee minimum moves.
Practice note: All listed BFS problems on this page now have dedicated solution write-ups, so you can move from the concept page straight into a worked example for each pattern.

โ† Back to Graph problems