Learning pathsPricingChecking sign-in…
Trees, graphs and optimization

Breadth-first search

Explore unweighted distance in layers.

A FIFO frontier processes equal-weight graph paths in nondecreasing hop count.

Mechanism and state

Mark a vertex when enqueuing, not when later removing it. For multi-source spread, enqueue every initial source at time zero. Freeze queue size for a minute and process exactly that many entries; newly discovered cells belong to the next minute. A fresh-cell counter distinguishes complete infection from an unreachable remainder. Tree level order uses the same frozen-size boundary: allocate a fresh row, remove exactly the captured count, and enqueue left before right. Proper-tree ownership makes separate visited state unnecessary. Walls and Gates seeds every gate at distance zero and writes the first distance into a fresh output matrix. Shortest Path in Binary Matrix uses eight-neighbor adjacency and seeds distance one because its answer counts cells. Word Ladder represents words as implicit vertices; generating one-letter changes avoids constructing every pairwise edge. Remove dictionary words on discovery, preserving the caller list. Explicit per-entry distances can replace frozen layer sizes when elapsed rounds are not needed. Kahn traversal propagates zero incoming dependencies; terminal safety instead propagates zero outgoing obligations through reverse edges. Course ordering uses FIFO to produce any valid permutation. Alien Dictionary first derives distinct first-mismatch inequalities, rejects invalid prefix order, and uses a minimum-priority frontier for the smallest valid alphabet. Parallel Courses freezes readiness batches into semesters; Longest Increasing Path freezes reverse-DAG batches into maximum suffix lengths. Unequal traversal costs require a frontier ordered by cost rather than hop count. For weights exactly zero or one, DSA-116 pushes strict zero-cost improvements to the deque front and one-cost improvements to the back. Store immutable cost snapshots so obsolete entries can be rejected.

Why the pattern works

Every first discovery has minimum hop distance: a shorter route would have been explored in an earlier layer. Marking on discovery ensures a single claim even when two sources share a neighbor. For component counting, FIFO order is optional; for minimum unit-time arrival, the layer invariant is essential. With many sources, first discovery minimizes over all source paths simultaneously. Reversing a graph supports destination reachability, but each ocean must retain a separate discovery owner. A target can return when popped without exhausting the frontier; only the returned target distance is guaranteed, not a complete all-vertex distance table. Topological readiness is a dependency certificate, not merely BFS distance. Frozen parallel-course layers realize the longest prerequisite chain under unlimited capacity and unit duration. Reverse matrix layers wait for every greater successor and realize a maximum recurrence. Minimum-priority source choice proves lexicographic prefix optimality when that extra output guarantee is requested. In 0–1 BFS, stored deque costs remain in nondecreasing order within two consecutive levels d and d+1. A front pop at d inserts only d at the front or d+1 at the back. A stale pop inserts nothing. Thus a valid front cost is minimal, giving nonnegative shortest-path finality and one valid scan per vertex.

Work through an example

[2,1,1] needs two minutes, not one. [2,1,1,1,2] needs two because both sources act together. [2,0,1] is impossible because empty cells interrupt the path. A room between two gates takes the nearer distance even on a tie; MAX means undiscovered during the search and unreachable only after exhaustion. [[0,1],[1,0]] has a two-cell diagonal path despite both orthogonal neighbors being blocked. hit→hot→dot→dog→cog uses four edits but returns five words. Identical begin/end returns one after validating the dictionary. With 0→1 cost one, 0→2 cost zero, and 2→1 cost zero, the deque processes vertex two before the old proposal for one. Vertex one improves to zero; its old cost-one snapshot is stale. A FIFO queue with visited-on-enqueue would miss this route.

Where the reasoning fails

Using a dynamically growing queue length inside the same round lets newly discovered cells act too soon. Weighted delays invalidate FIFO shortest-time reasoning and require a different priority mechanism. Mutating the grid saves a visited matrix but does not remove queue memory. Tree BFS retains O(w) queue space, excluding O(n) returned values and per-depth row objects; a chain has a narrow queue but many output rows. Declare distance units: gates count edges, binary paths count cells, and ladders count words. Source zero means an open binary cell but zero in its separate distance matrix means undiscovered. Word generation in Java copies and hashes O(L) characters per String, so 25L candidates per vertex cost O(L²), not O(L). Dictionary duplicates are one vertex. Mark-on-pop permits duplicate frontier owners; one global ocean mask loses the intersection. A queue that drains newly released courses in the same round collapses a chain into one semester. Sorted initial seeding does not make FIFO globally smallest. Keep duplicate-degree counts and stored edge occurrences consistent; Alien Dictionary deduplicates both. Intermediate release states still include pending edges of the current popped vertex. An empty optional alphabet is a successful empty String, distinct from an absent Optional. Binary BFS measures weight sum, not hop count. A zero-cost cycle must not re-enqueue equal candidates. Allowing weight two breaks the two-level insertion proof; use a general heap or prove a bucket scheme. A grid target discovered early may still improve and must be finalized before an early return.

Reconstruct the reasoning

Show queue, grid, fresh count, and elapsed minutes at each layer boundary. Explain exactly when a cell changes from undiscovered to claimed. Trace all-source gate distances and distinguish an unreachable MAX room from one not yet discovered. Explain the diagonal two-cell path and an open-endpoint but disconnected example. Trace duplicate cog entries in the ladder, recording word counts, unused membership, and the unprocessed frontier on target return. State which APIs preserve input, mutate cells, or allocate fresh output, and include row validation when a grid has zero columns. Trace a diamond plus an isolated course for both one valid order and minimum semesters. Contrast [course, prerequisite] with [before, after] pair formats. Infer constraints from za,zb,ca,cb and prove why a newly ready b precedes queued z under the smallest-alphabet rule. Trace a long increasing matrix suffix and justify why reverse layers compute a maximum rather than a shortest path. Write every stored deque pair after each insertion in DSA-116, including the stale pair. Then use a threshold BFS to decide whether a grid route can keep every jump under T, and explain the monotone predicate behind the alternative DSA-115 solution.

Apply this foundation

Your study notes