4 km3 km2 km5 km6 kmABCEA: B CB: A CC: A B DD: CE: FF: E10 entriesDF A B C D E FA 0 1 1 0 0 0B 1 0 1 0 0 0C 1 1 0 1 0 0D 0 0 1 0 0 0E 0 0 0 0 0 1F 0 0 0 0 1 036 cells
Towns: the verticesRoads: the edges (signs show their length once weighted)Adjacency list: one line of neighbours per townAdjacency matrix: a row and a column per townSix towns are the vertices and five roads are the edges. The adjacency list card gives each town one line naming its neighbours; the adjacency matrix card has a row and a column per town, with 1 where a road joins them. The car drives an edge, a path and a cycle. Closing road B–C leaves a tree; making C → D one-way makes the matrix lopsided; giving roads lengths puts the lengths in both cards. For V vertices and E edges, an adjacency matrix always has V × V cells, while an adjacency list holds 2E entries for an undirected graph (E for a directed one), plus one list per vertex.

Vertices and edges

  1. A graph is a set of vertices joined by edges. Here each town is a vertex and each road is an edge: 6 vertices, 5 edges. Swap towns for people and roads for friendships, and the same picture is a social network.

Storing a graph

Paths and cycles

Direction and weight

Try it in the Python prompt

;; step 1/11 · Vertices and edges
>>> towns = ["A", "B", "C", "D", "E", "F"]
>>> roads = [("A", "B"), ("A", "C"), ("B", "C"), ("C", "D"), ("E", "F")]
>>> len(towns), len(roads)
(6, 5)

The towns, roads and distances are a made-up example, kept small so the whole matrix fits on one card. For V vertices and E edges, an adjacency matrix always has V × V cells, while an adjacency list holds 2E entries for an undirected graph (E for a directed one), plus one list per vertex.