Chris Collins

Tools · math

Graph algorithms

Draw a graph (or open one of the book's) and step through the classic algorithms one move at a time: degrees, components and Euler trails; the adjacency matrix and walk counts; BFS racing DFS through a maze; Dijkstra and Bellman–Ford (with a negative edge and currency arbitrage); Kahn's topological sort and the critical path; Kruskal and Prim; greedy and bipartite colouring; Hamiltonian tours by brute force against nearest neighbour; and PageRank by random surfers and power iteration.

Added

Works with

  • Coding interviews Interview preppractise the interview problems built on these algorithms — BFS, topological sort, Dijkstra and union-find — in JavaScript or Python
How to use it

One graph, nine algorithms. Draw the graph once and switch tabs to run a different algorithm on it, or press one of the Book examples buttons on each tab to load the example the book works through. Every algorithm moves one step per click of Step ▶, with ◀ to go back, ▶▶ Run / ⏸ Pause (slow, normal, fast or turbo), ⏮ and ⏭, and the arrow keys when the step buttons have focus. A message under the drawing says what the last move did, and a state table fills in row by row in the same layout as the book’s hand traces.

Drawing a graph

The tools above each drawing:

  • ✋ Move — drag a vertex. On tabs with a start vertex, tapping a vertex makes it the start.

  • + Vertex — tap empty space to add a vertex (named A, B, C … or 0, 1, 2 …); tap a vertex to rename it.

  • / Edge — drag from one vertex to another, or tap one and then the other.

  • # Weight — tap an edge to set its weight (negative weights are allowed); tap a vertex to give it a weight, which the topological-sort tab uses as a task duration.

  • ✕ Erase — tap a vertex or an edge to delete it.

  • ↶ Undo, ◯ Circle (lay the vertices out on a circle) and Clear; tick directed or weighted to change the kind of graph.

The edge list box shows the same graph as text and accepts typing: A-B is an undirected edge, A>B an arrow, A-B:4 an edge of weight 4, and a bare A or A:3 a vertex (with a weight). Parallel edges are allowed (Königsberg needs them). Vertex names are letters, digits and _.

⛶ Full screen (or F) gives the drawing the whole screen — the browser’s full screen where it is allowed, otherwise a full-window layer (iPhone); it is redrawn as the window changes, and ◫ Panels hides the controls and tables beside it. Escape leaves.

The tabs

  • Draw & Euler — each vertex’s degree (in and out for a directed graph), the handshake lemma Σ deg = 2|E| side by side, connected components in different colours (and strongly connected components for a directed graph), and whether an Euler path or circuit exists, with the odd-degree vertices ringed in red. When one exists, stepping traces it edge by edge with Hierholzer’s algorithm. Simple graphs also get the planarity test E ≤ 3V − 6 (E ≤ 2V − 4 when triangle-free), which proves K₅ and K₃,₃ non-planar.

  • Matrix & walks — the adjacency matrix, linked to the drawing: hover a cell to find its edge, click it to add or remove the edge. Below it, Aʳ for r from 1 to 8; click a cell to list the walks it counts and trace one on the drawing.

  • BFS vs DFS — the two searches side by side from the same start, with the queue and the stack shown live, BFS distances and DFS discovery order on the vertices, and the route each finds to the exit. Maze mode swaps the graph for a 12 × 12 maze with a few loops: BFS floods outward in rings while DFS snakes down corridors. DFS here is the book’s recursive visit(), so its stack is the current path.

  • Shortest paths — Dijkstra, one move per finished vertex and one per relaxed edge, with the book’s trace table (step, finished vertex, then distance (parent) for every vertex); or Bellman–Ford, one move per edge relaxation with a row per pass, and a final check pass that finds negative cycles. Negative edge loads the book’s three-vertex example; whenever a weight is negative, Dijkstra’s answers are compared with the true distances and the wrong ones shown in red. rates (−ln) treats weights as exchange rates and uses −ln(rate), which turns the book’s arbitrage example into a negative cycle.

  • Topological sort — Kahn’s algorithm with ties taken alphabetically, as in the book: in-degrees on the vertices, the ready set, and the book’s table (take, in-degree changes, ready afterwards). If it gets stuck, the leftover vertices and a cycle among them are shown. Give the vertices weights (durations) and the critical-path table fills in alongside: earliest start and finish, latest finish and slack, with the critical path drawn in red.

  • Spanning trees — Kruskal, with the sorted edge list, the keep/skip table and the union–find forest (vertices coloured by the root of their component); or Prim from a start vertex, with the cheapest known link to each outside vertex.

  • Colouring — greedy colouring in an order you choose (as listed, alphabetical, largest degree first, DSatur, a typed order, or Shuffle), compared with the exact chromatic number found by search; or two-colouring by BFS, which either splits the graph into two sides or finds an odd cycle.

  • Tours — Hamiltonian cycles and the travelling salesman problem: brute force over every order of the other vertices (each cycle counted once, not once per direction; up to 9 vertices), showing the tour being checked and the best so far, against nearest neighbour, which is fast but can be badly wrong.

  • PageRank — power iteration on the Google matrix G = dM + (1 − d)/n·J, one iteration per step, next to a crowd of 2,000 random surfers who make one hop per step (follow a random link with probability d, otherwise teleport). Pages are sized by rank; the bar chart compares the exact vector with the share of surfers on each page, and a log plot shows the step size shrinking by about d per iteration. The damping slider runs from 0 to 1; untick dead ends teleport to let probability leak out of pages with no links (watch the total fall below 1 at d = 1).

A note on A³

The diagonal of A³ counts closed walks of length 3, which are not quite triangles. In an undirected graph each triangle through a vertex v can be walked two ways round (v→a→b→v and v→b→a→v), so it adds 2 to (A³)ᵥᵥ: the number of triangles through v is (A³)ᵥᵥ / 2, and the total number of triangles is trace(A³) / 6. In a directed graph without loops each directed 3-cycle adds 1 at each of its three vertices, so there are trace(A³) / 3 of them. The Matrix & walks tab shows all three numbers for the current graph; the ch25-triangles example makes the factor of 2 visible.

Limits

  • Brute-force tours stop at 9 vertices (20,160 tours for an undirected graph); the matrix view at 14 vertices; the exact chromatic number at 22.

  • Spanning trees and colouring ignore arrow directions. Topological sort needs a directed graph.

  • PageRank treats an undirected edge as a link each way and counts parallel links once.

  • The surfers use a fixed random seed, so the same graph and d always give the same crowd.

  • Shortest paths use the cheapest of any parallel edges.

Related: Matrix calculator (powers and eigenvectors of an adjacency matrix), Linear systems, visually, Matrix transformations and Big-O (how these algorithms scale).

Linking to an example

Share link copies a URL that reopens the tool with your graph and settings. Links can also be written by hand: the parameters below set the state, and the part after # picks the tab (draw, matrix, search, paths, dag, mst, colour, tour, rank). For example, /tools/graph-algorithms/?g=S-A:4,S-B:2,A-B:1,B-T:5&src=S&to=T#paths opens a small weighted graph in the shortest-paths tab.

Parameter Meaning Example

example

a book example (below); other parameters override its settings

example=ch25-dijkstra

g

the graph as an edge list: A-B undirected, A>B directed, :w a weight, a bare name a vertex (foundation:3 a vertex with a weight); separate with commas

g=A-B:4,B-C:2,C>A

dir

1 makes every edge an arrow (A>B in g does this by itself)

dir=1

xy

vertex positions as name:x:y, in percent of the drawing (0–100)

xy=A:10:50,B:90:50

src

the start / source vertex

src=S

to

the target or exit vertex (search and shortest paths)

to=T

algo

dijkstra or bf (shortest paths); kruskal or prim (spanning trees); greedy or two (colouring); brute or nn (tours)

algo=bf

order

greedy colouring order: given, abc, degree, dsatur, or a list of vertices

order=a1,a2,a3,a4,b1,b2,b3,b4

r

the power of A on the matrix tab (1–8)

r=3

d

the PageRank damping factor (0–1)

d=0.5

dead

0 lets probability leak out of dead ends instead of teleporting

dead=0

log

1 treats weights as exchange rates and uses −ln(rate)

log=1

maze

a maze seed for the search tab (0 = use the graph)

maze=25

step

open at this move of the algorithm

step=3

Typing a link: > and : can be typed as they are; a browser sends them as %3E and %3A, which work too. Do not use + in an edge list: in a URL it means a space. Spaces, commas and semicolons all separate edges.

Book examples (?example=…; each opens on its own tab):

Example Shows

ch25-konigsberg

the seven bridges: degrees 3, 5, 3, 3, so no Euler path

ch25-house

the open envelope: an Euler path from S to T

ch25-two-triangles

all degrees even but disconnected: no Euler circuit

ch25-ex-euler

the exercise graph AB, AC, BC, BD, CD, DE: neither

ch25-k5

K₅: E = 10 > 3V − 6 = 9, not planar

ch25-k33

three houses and three utilities: E = 9 > 2V − 4 = 8, not planar

ch25-walks

the directed example with A² and A³ as printed in the book

ch25-triangles

closed 3-walks against triangles in an undirected graph

ch25-bfs

the A–H graph: BFS visits A B C D E F G H, DFS A B D C E F H G

ch25-maze

BFS against DFS in a 12 × 12 maze

ch25-ex-bfs

the exercise: BFS from vertex 1

ch25-dijkstra

the fully worked Dijkstra trace: S B A C D T, length 12

ch25-dijkstra-negative

S→A 2, S→B 3, B→A −2: Dijkstra says 2, the truth is 1

ch25-bellman-ford

the same graph by Bellman–Ford

ch25-ex-dijkstra

the exercise: A C B D E, length 8

ch25-mastery-dijkstra

the mastery check: S 0, A 1, B 3, C 4

ch25-arbitrage

USD → EUR → GBP → USD at 0.90, 0.90, 1.25: a negative cycle

ch25-toposort

Kahn’s algorithm on the book’s dependency map

ch25-toposort-cycle

the same map with graphs → logic added: no order exists

ch25-critical-path

the building job: 10 weeks, plumbing has 4 weeks of slack

ch25-ex-toposort

the exercise’s build pipeline

ch25-mst

Kruskal: BC, BD, AC, EF, CE, total 14

ch25-prim

the same tree grown by Prim from A

ch25-mastery-mst

the mastery check: total 7

ch25-exams

exam scheduling: 3 slots

ch25-crown-bad

the crown graph in the interleaved order: 4 colours

ch25-crown-good

the crown graph with the a’s first: 2 colours

ch25-square

two-colouring the square

ch25-triangle

two-colouring fails on the triangle

ch25-developers

developers and services: bipartite

ch25-cube

the cube: 6 Hamiltonian cycles

ch25-tsp

six towns: nearest neighbour costs 28, the best tour 20

ch25-pagerank

the PageRank teaser with pages 0–3

ch28-pagerank

the tiny web: A 0.3725, B 0.1958, C 0.3941, D 0.0375 after 47 iterations

ch28-pagerank-bd

the exercise: add a link B → D

ch28-link-farm

two extra pages that both link to D

ch28-dead-end

a dead end and a closed loop at d = 1, with leaking dead ends

Runs entirely in your browser; nothing you type leaves this page.