← back to algorithms

Graphs

Nievergelt & Hinrichs · Ch. 6 · Algorithms and Data Structures

A graph is vertices and edges. Represent it as an adjacency list (sparse) or adjacency matrix (dense). BFS explores level by level. DFS explores depth-first. Both run in O(V + E).

A d=0 B d=1 C d=1 D d=2 E F G d=2 BFS from A: frontier expands one level at a time

Adjacency list representation

Scheme

Breadth-first search

BFS uses a queue. It visits all vertices at distance d before any at distance d+1. This gives shortest paths in unweighted graphs.

Scheme

Depth-first search

DFS uses a stack (or recursion). It explores as deep as possible before backtracking. Useful for topological sort, cycle detection, and connected components.

Scheme
Neighbors

Cross-references