CLRS Graph Algorithms

Pseudocode

O(V + E)
BFS(G, s)
1for each vertex u ∈ G.V − {s}
2u.color = WHITE
3u.d = ∞
4u.π = NIL
5s.color = GRAY
6s.d = 0
7s.π = NIL
8Q = ∅
9ENQUEUE(Q, s)
10while Q ≠ ∅
11u = DEQUEUE(Q)
12for each vertex v ∈ G.Adj[u]
13if v.color == WHITE
14v.color = GRAY
15v.d = u.d + 1
16v.π = u
17ENQUEUE(Q, v)
18u.color = BLACK

Adjacency List

BFS

Breadth-first search explores a graph in layers from a chosen source vertex.

Input

An unweighted graph and a source vertex.

Output

The distance in edge count from the source and the BFS predecessor tree.

Behavior

It uses a queue, discovering all vertices at distance k before any at distance k + 1.

Best Use

Use it for shortest paths in unweighted graphs or level-by-level reachability.

Test Example

Shortest Hops In A Social Graph

Starting at s, an exam may ask for each vertex's shortest unweighted distance and BFS parent.

The important move is to group vertices by discovery level. Every edge from the current frontier is checked before moving to the next distance.

BFS discovers s, then {a, b}, then {c, d}; the level number is the shortest number of edges.

BEFOREAFTER BFS FROM ssabcded=0d=1d=2 / 3sd=0ad=1bd=1cd=2dd=2ed=3Green edges form one BFS tree.Dashed edges were examined but not chosen.
How to use this visualizer
Which graph algorithms can I visualize?
Use BFS or DFS for traversal, Kruskal or Prim for minimum spanning trees, Bellman–Ford or Dijkstra for single-source shortest paths, Floyd–Warshall for all-pairs shortest paths, and Ford–Fulkerson or Push–Relabel for maximum flow.
How do I enter a graph?
Write one vertex per line, followed by its neighbors. Add a weight as neighbor:weight, for example B:4. For Floyd–Warshall, use a square weight matrix and enter ∞ for missing edges. You can also start from a built-in example.
What can I see at each step?
Start the algorithm to highlight the current line of pseudocode and inspect the graph and algorithm state. The workspace shows the relevant distances, predecessors, queues, stacks, matrices, or flows as you step forward and backward.