Storing a graph
After this: Build an adjacency list, and say when an adjacency matrix is the better choice.
On this page · 7 sections · 4 checks
In the first lesson you drew a graph as circles and lines. A program cannot read a drawing, so it needs the same information as data. This lesson shows the two standard ways to store a graph.
First way: a list of neighbours for each node
Here are the four friends again.
Write down each person, and next to each person write the people they know.
| Person | Knows |
|---|---|
| Asha | Ben, Cara |
| Ben | Asha, Dev |
| Cara | Asha, Dev |
| Dev | Ben, Cara |
This holds everything in the drawing. It is called an . "Adjacent" means "next to", so it lists the nodes next to each node.
Notice that the edge between Asha and Ben appears twice: once in Asha's row and once in Ben's row. An edge that works both ways, like friendship, is called . A one-way edge, drawn as an arrow, is called . Every undirected edge goes in the list twice, once from each end, so four edges give eight entries.
In code, we store this as a dictMap. Each key is a node, and each value is the list of that node's neighbours. The hash-maps tutorial explains how this works.
friends = { "Asha": ["Ben", "Cara"], "Ben": ["Asha", "Dev"], "Cara": ["Asha", "Dev"], "Dev": ["Ben", "Cara"],}
print(friends["Ben"])print("Dev" in friends["Asha"])['Asha', 'Dev'] False
Map<String, List<String>> friends = new HashMap<>();friends.put("Asha", List.of("Ben", "Cara"));friends.put("Ben", List.of("Asha", "Dev"));friends.put("Cara", List.of("Asha", "Dev"));friends.put("Dev", List.of("Ben", "Cara"));
System.out.println(friends.get("Ben"));System.out.println(friends.get("Asha").contains("Dev"));[Asha, Dev] false
The first print looks up Ben's list. The second print asks whether Dev is in Asha's list, and he is not.
Building the lists in a loop
A program usually receives the edges as pairs, and it builds the lists in a loop. For the pair A–B, it adds B to A's list and A to B's list.
nodes = ["A", "B", "C", "D", "E", "F"]edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E"), ("E", "F")]
adj = {node: [] for node in nodes} # a dict of lists: a hash map, key → neighboursfor a, b in edges: adj[a].append(b) # the edge, seen from one end adj[b].append(a) # and from the other: undirectedfor node in adj: adj[node].sort() # neighbours alphabetical, as in the visualizer
print(adj["D"])['B', 'C', 'E']
String[] nodes = {"A", "B", "C", "D", "E", "F"};String[][] edges = {{"A", "B"}, {"A", "C"}, {"B", "D"}, {"C", "D"}, {"D", "E"}, {"E", "F"}};
Map<String, List<String>> adj = new LinkedHashMap<>(); // a map of lists: key → neighboursfor (String node : nodes) adj.put(node, new ArrayList<>());for (String[] e : edges) { adj.get(e[0]).add(e[1]); // the edge, seen from one end adj.get(e[1]).add(e[0]); // and from the other: undirected}for (List<String> ns : adj.values()) Collections.sort(ns); // neighbours alphabetical, as in the visualizer
System.out.println(adj.get("D"));[B, C, E]
nodesandedgesare the input for the six-node graph.adj, short for adjacency, starts with an empty list for every node.- The highlighted lines add each edge from both ends.
- The next loop sorts each list. A graph does not need this. It means that every walk in this tutorial gives the same result when you work it out by hand.
- The last line prints D's list.
Second way: a table of ones and zeros
Make a table with one row and one column for each person. Put a 1 in a cell if those two people know each other, and a 0 if they do not.
| Asha | Ben | Cara | Dev | |
|---|---|---|---|---|
| Asha | 0 | 1 | 1 | 0 |
| Ben | 1 | 0 | 0 | 1 |
| Cara | 1 | 0 | 0 | 1 |
| Dev | 0 | 1 | 1 | 0 |
Try two questions on this table.
- Does Ben know Cara? Row Ben, column Cara holds 0, so he does not. You looked at one cell.
- Who does Ben know? Read all of row Ben and pick out the 1s: Asha and Dev. You looked at four cells.
This table is called an . "Matrix" is the mathematical word for a table of numbers. Each undirected edge sets two cells: row Asha, column Ben, and also row Ben, column Asha. In code, it is a table of numbers with the nodes numbered from 0.
What each one costs
Cost means the number of steps, and Counting steps explains the notation in full. Here, n is the number of nodes.
- O(1) means the work stays the same, however big the graph is.
- O(n) means the work grows at the same rate as the number of nodes.
- O(n²) means the work grows with n × n: double the nodes, and you get four times the work.
The of a node is the number of neighbours it has. D has degree 3, and F has degree 1. In this table, u and v stand for any two nodes.
| Question | Adjacency list | Adjacency matrix |
|---|---|---|
| Is there an edge between u and v? | read u's list: O(degree of u) | look at one cell: O(1) |
| Which nodes are u's neighbours? | the list holds them: O(degree of u) | read all of row u: O(n) |
| How much memory does it use? | one key per node, two entries per edge: O(n + edges) | one cell per pair of nodes: O(n²) |
Now try a real example. A town has 1,000 junctions, and each has about four roads. The list holds about 4,000 neighbour entries. The matrix holds 1,000 × 1,000 = 1,000,000 cells, and almost all of them hold 0.
A graph like this, with far fewer edges than it could have, is called . Most real graphs are sparse, and the coming walks ask for a node's neighbours again and again. So the adjacency list is the usual choice, and every code example from here on uses it. The matrix is better when most pairs of nodes are joined, or when the main question is "is there an edge?".
Watch it happen
This is the six-node graph. The button runs a walk, and the next lesson explains how the walk moves. For now, use it to see the lists: each visit reads the list stored under that node.
- BFS from DRun a walk from D. The next lesson explains how the walk moves. The first visit names D's neighbours in alphabetical order: B, C, E. That is the list stored under D.
- BFS from F
Pick a start node and run an algorithm.
Check yourself
What does this print?
nodes = ["A", "B", "C", "D", "E", "F"]edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E"), ("E", "F")]
adj = {node: [] for node in nodes} # a dict of lists: a hash map, key → neighboursfor a, b in edges: adj[a].append(b) # the edge, seen from one end adj[b].append(a) # and from the other: undirectedfor node in adj: adj[node].sort() # neighbours alphabetical, as in the visualizer
print(adj["D"])String[] nodes = {"A", "B", "C", "D", "E", "F"};String[][] edges = {{"A", "B"}, {"A", "C"}, {"B", "D"}, {"C", "D"}, {"D", "E"}, {"E", "F"}};
Map<String, List<String>> adj = new LinkedHashMap<>(); // a map of lists: key → neighboursfor (String node : nodes) adj.put(node, new ArrayList<>());for (String[] e : edges) { adj.get(e[0]).add(e[1]); // the edge, seen from one end adj.get(e[1]).add(e[0]); // and from the other: undirected}for (List<String> ns : adj.values()) Collections.sort(ns); // neighbours alphabetical, as in the visualizer
System.out.println(adj.get("D"));You want to know whether A–F is an edge. What does that cost with each way of storing the graph?
A road map has 10,000 junctions and 20,000 roads. Which way of storing it is better, and why?
Complete the loop: add the same edge seen from be[1], so that the graph is undirected.
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("D", "E"), ("E", "F")]adj = {node: [] for node in "ABCDEF"}for a, b in edges: adj[a].append(b) ____________________ # ← the same edge, seen from bprint(adj["D"])String[][] edges = {{"A", "B"}, {"A", "C"}, {"B", "D"}, {"C", "D"}, {"D", "E"}, {"E", "F"}};Map<String, List<String>> adj = new LinkedHashMap<>();for (String node : "ABCDEF".split("")) adj.put(node, new ArrayList<>());for (String[] e : edges) { adj.get(e[0]).add(e[1]); ____________________ // ← the same edge, seen from e[1]}System.out.println(adj.get("D"));Connect
- Build an adjacency list as a map of lists, adding each undirected (two-way) edge from both ends.
- Say what it costs to list a node's neighbours and to check for an edge, on a list and on a matrix.
- Choose the list for a sparse graph, and say why the matrix wastes space there.