PrepStack · Markdown HTML

BFS connectivity traversal

Traversal and connectivity · HTML

Formal shape

Enqueue every unseen start, repeatedly dequeue a vertex and discover its unseen neighbors, and scan all vertices outside the search to partition G.

Recognition signals

False friends

SignalWhy it is different
Unequal-weight shortest pathFIFO does not order total cost; use Dijkstra or 0-1 BFS.
Topological layersA dependency layer is governed by remaining indegree, not geometric distance from an arbitrary source.

Core invariant

Every queued vertex is discovered and assigned to the current component but not fully expanded; an unseen vertex is not yet proven reachable from this start.

State, transition, and processing order

ItemDefinition
StateFIFO queue, visited set, component ID, and optional parent or level maps.
TransitionDequeue u; immediately mark and enqueue each eligible unseen neighbor v.
Frontier / orderA FIFO queue preserving discovery order, so one layer is expanded before the next.

Python skeleton

from collections import deque

def bfs_groups(graph):
    seen, label = set(), {}
    group_id = 0
    for start in graph:
        if start in seen:
            continue
        seen.add(start)
        q = deque([start])
        while q:
            u = q.popleft()
            label[u] = group_id
            for v in graph[u]:
                if v not in seen:
                    seen.add(v)
                    q.append(v)
        group_id += 1
    return group_id, label

Correctness sketch

  1. Each enqueue follows an actual edge from an already reachable vertex, so no foreign component is admitted.
  2. Induction along any path proves that every reachable vertex is eventually discovered.
  3. Discovery-time marking assigns each vertex once; the outer scan starts all remaining components.

Complexity

TimeSpaceParameters
O(V+E)O(V)V is the vertex count and E the total adjacency size; the queue can be as wide as V.

Edge cases

Error patterns

PatternWhy it fails / fix
Using list.pop(0)Element shifting makes dequeue linear; use deque.popleft.
Marking after dequeueA diamond can enqueue the same vertex multiple times.
Generalizing first discovery to all weightsOnly equal-cost edges make a BFS layer equal minimum cost.

Selection and exclusion rules

RelationTemplateBoundary
adds distance semanticsUnweighted shortest-path BFSThe question changes from reachability to fewest steps.
common decision engineBinary search on the answercan(x) checks connectivity under a threshold.
interchangeable traversalDFS components and reachabilityRecursive aggregation is more natural than layers.
similar queue shapeTopological sort / indegree eliminationRemember admission is indegree zero, not first reachability.

Original micro-example

PartDetail
ResultLabels can be a,b,c,d→0 and e→1.
Setupa touches b and c; c touches d; e is isolated.
TraceDequeuing a enqueues b/c; c later discovers d. After that queue drains, e starts another search.

Recall prompts

My notes