PrepStack · Markdown HTML

Unweighted shortest-path BFS

Ordered frontier and path · HTML

Formal shape

Set dist[s]=0. FIFO expands vertices in nondecreasing distance; the first discovery of v assigns dist[v]=dist[u]+1.

Recognition signals

False friends

SignalWhy it is different
Weights of both 0 and 1Small is not equal; FIFO layers cease to equal cost, so use 0-1 BFS.
Reachability onlyIf distance is unused, component BFS or DFS is enough; avoid unnecessary layer machinery.

Core invariant

Dequeued distances are nondecreasing, and a vertex's discovery distance is the minimum edge count from any source.

State, transition, and processing order

ItemDefinition
StateFIFO queue, dist map that can also serve as visited, current state, and optional parent map.
TransitionGenerate each eligible unseen neighbor v of u, set dist[v]=dist[u]+1, and enqueue it.
Frontier / orderA FIFO queue whose head belongs to the smallest pending layer because every edge adds exactly one.

Python skeleton

from collections import deque

def shortest_steps(start, is_goal, neighbors):
    q = deque([start])
    dist = {start: 0}
    while q:
        u = q.popleft()
        if is_goal(u):
            return dist[u]
        for v in neighbors(u):
            if v not in dist:
                dist[v] = dist[u] + 1
                q.append(v)
    return -1

Correctness sketch

  1. FIFO completes layer d before d+1, so dequeue distances never decrease.
  2. If a first-discovery path were not shortest, a predecessor on a shorter path would have appeared in an earlier layer and discovered the same vertex first.
  3. When a goal is dequeued, every potentially shorter state has already been expanded, making early exit safe.

Complexity

TimeSpaceParameters
O(V+E)O(V)V and E count reachable states and generated transitions, including in an implicit graph.

Edge cases

Error patterns

PatternWhy it fails / fix
Returning on generated goalIt is correct for standard equal-cost BFS, but checking after pop gives a safer reusable frontier convention.
Off-by-one layer countersA distance stored per vertex is often more robust than manual round increments.
Mixing validity with visitedValidate a generated state before testing whether it was discovered.

Selection and exclusion rules

RelationTemplateBoundary
nonnegative-weight generalizationDijkstra nonnegative shortest pathEdges have several nonnegative costs.
alternativeGrid dynamic programmingFour-way equal-cost movement asks for minimum steps.
analogyTree level-order BFSThe shallowest layer equals minimum edge count.
two-weight generalization0-1 BFSSome moves are free and others cost one.

Original micro-example

PartDetail
ResultThe minimum is 3 moves, for example 0→2→4→5.
SetupA state x can become x-1 or x+2 per move; go from 0 to 5.
TraceLayer 0={0}; layer 1={-1,2}; layer 2 includes 1 and 4; layer 3 first reaches 5.

Recall prompts

My notes