Graph
G=(V,E) has vertices and edges; edges may be directed or undirected and may carry weights. A path follows consecutive edges.
REFERENCE SHEET
Choose a traversal based on edge weights, direction, and the question being asked.
Before this Data structures & amortized cost, Asymptotics & recurrences
G=(V,E) has vertices and edges; edges may be directed or undirected and may carry weights. A path follows consecutive edges.
Breadth-first search uses a queue to explore layers. Depth-first search follows a branch before backtracking, using recursion or a stack.
The minimum total edge weight over source-to-target paths when a finite minimum exists. Unreachable vertices have distance +∞.
On an unweighted graph, BFS finds minimum-edge-count distances from a source. With adjacency lists, its time is O(|V|+|E|).
For nonnegative edge weights, repeatedly settling the smallest tentative distance and relaxing outgoing edges yields shortest paths. A binary-heap implementation takes O((|V|+|E|) log |V|).
In a directed acyclic graph, relax vertices in topological order in O(|V|+|E|). Negative weights are allowed because there are no directed cycles.
Shortest paths model travel, communication, and navigation costs.
A topological ordering schedules prerequisites in a DAG; no such ordering exists when a directed cycle is present.
01 / Compute
Compare reaching a directly with reaching it through b.
s→b→a→t costs 1+2+1=4, beating s→a→t of cost 5.
02 / Explain
BFS optimizes a different objective.
BFS reaches t in one edge through s→t, but the two-edge path costs only 2. Minimum edge count and minimum weight disagree.
Further reading and full-length treatments: