Meet vertices and edges, directed, undirected and weighted, see a graph as an adjacency list and as a matrix, count degrees, build a graph from a list of pairs, and build your own.
You are building the route planner for a city metro. Stations are the things, and each pair of stations that a train connects directly is a link. A rider asks, "From here, where can I go in one stop?"
A list of stations cannot answer that, because the answer lives in the links, not in the stations. You need a structure that stores both the things and the links between them.
Picture the map on the wall of a station. Circles are stations, and lines between them are tracks. The map only tells you which stations are joined.
Your friends on a chat app work the same way. Each person is a circle, and each friendship is a line between two circles.
A metro map is a graph. Stations are the vertices, and each track between two stations is an edge.
A graph is a set of vertices (the things, also called nodes) and edges (the links, each joining two vertices). Vertices are usually numbered 0, 1, 2, and so on, so that a program can use the number as a position.
Edges come in a few kinds.
Two vertices joined by an edge are neighbours. The degree of a vertex is the number of edges that touch it. A vertex with no edges at all is isolated, like a station whose line is closed.
A tree, from the last module, is a graph with no cycles (no route that leads back to its start) and one route between any two vertices. A general graph has no such rules: it can have cycles, many routes between two vertices, and parts that do not connect at all.
Step by step: One graph, stored as a list and as a matrix. The animated player loads in your browser.
Predict what happens
Q A chat app stores friendships as an undirected graph. Ana and Ben are friends. Which statement must be true?
Answer: B
An undirected edge has no direction, so it is a link in both ways. The degrees of Ana and Ben can be different, and the graph can hold many more people.
You have a drawing. A program needs numbers in memory. There are two usual ways to store a graph, and they trade memory for speed in different places.
An adjacency list keeps, for each vertex, the list of its neighbours. Think of a phone book where every person has a short list of the people they know. A graph with n vertices has n lists. Each edge shows up as one entry (a directed edge) or two entries (an undirected edge, once at each end).
The memory is about n + m for n vertices and m edges. Reading the neighbours of u is reading one list, so it costs the degree of u, however big the graph is.
An adjacency list keeps, for each vertex, the list of its neighbours. An undirected edge is stored at both ends.
An adjacency matrix is a grid with a row and a column for every vertex. Cell (u, v) holds 1 when there is an edge from u to v, and 0 when there is not. For a weighted graph, the cell holds the weight. An undirected graph has a matrix that is the same when you swap rows and columns.
A matrix answers "is there an edge between u and v?" with one read. But it always holds n times n cells, even when there are few edges. Listing the neighbours of u means reading a whole row of n cells.
An adjacency matrix is a grid with a row and a column for each vertex. A one in cell u, v means an edge.
Step by step: Add the edge 1 to 4. The animated player loads in your browser.
With a list, you scan the list of u and look for v. With a set in place of a list, the check is one lookup. With a matrix, it is one read of cell (u, v).
Step by step: Is there an edge between 0 and 3?. The animated player loads in your browser.
Predict what happens
Q A graph with 100,000 vertices stores each vertex's neighbours in a plain list. A vertex u has 3 neighbours. You ask whether u and v are joined. About how many entries do you read?
Answer: B
You open the list of u and scan it. It has 3 entries, so you read at most 3. The other 99,999 vertices are never touched.
To list the neighbours of u, read the list of u. Its length is the degree of u.
Step by step: The neighbours of 3. The animated player loads in your browser.
In a directed graph there are two degrees. The out-degree of u is the length of its list: edges leaving u. The in-degree counts edges arriving at u, and a list of out-neighbours does not store those with u. You either scan every list, or keep a second list of arrivals.
In a directed graph a vertex has an out-degree, the edges leaving it, and an in-degree, the edges arriving at it.
Step by step: Who follows whom: the degrees of 0. The animated player loads in your browser.
Exercise · Predict the output: How many edges arrive?. A directed graph has 5 vertices and the edges 0→1, 0→2, 1→2, 2→0 and 3→2, stored as lists of out-neighbours. This code counts the edges that arrive at each vertex. What does it print?
n = 5
edges = [(0, 1), (0, 2), (1, 2), (2, 0), (3, 2)]
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
incoming = [0] * n
for u in range(n):
for v in adj[u]:
incoming[v] += 1
print(*incoming)Predict what happens
Q An undirected graph has 6 edges. What do the degrees of all its vertices add up to?
Answer: B
Each edge adds one to the degree of each of its two ends, so the degrees add up to twice the number of edges, whatever the shape.
A weighted graph stores a number with each edge. In a list, each entry becomes a pair: the neighbour and the weight. In a matrix, the cell holds the weight, and a special value means no edge. Pick one that no real weight can take, such as infinity: if a road can take 0 minutes, 0 cannot mean "no road".
Step by step: A weighted graph: distances between stations. The animated player loads in your browser.
Exercise · Find the bug: The road that takes no time. This builds an adjacency matrix of road times and returns the minutes of the direct road between u and v, or -1 when there is no direct road. Sometimes it reports a road that does not exist. Which line is wrong?
def road_minutes(n, roads, u, v):
matrix = [[0] * n for _ in range(n)]
for a, b, minutes in roads:
matrix[a][b] = minutes
matrix[b][a] = minutes
return matrix[u][v]Real input is a list of edges: pairs such as (0, 1), (0, 2), (2, 3). You build the adjacency list in two steps. First, make an empty list for every vertex, so that isolated vertices exist too. Then read the pairs one at a time and add each one.
adj = [[] for _ in range(n)] # one empty list for every vertex
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # undirected: add it to both endsFor a directed graph, delete the last line. Building costs O(n + m): one pass over the vertices and one pass over the edges.
Trace it with n = 5 and the edges (0, 1), (0, 2), (2, 3). The lists come out as 0: [1, 2], 1: [0], 2: [0, 3], 3: [2] and 4: []. Three edges made six entries, and vertex 4 has an empty list because no pair names it.
The matrix of the same graph has 25 cells. Row 0 reads 0 1 1 0 0, and column 0 reads the same, because the graph is undirected. The degrees, 2, 1, 2, 1 and 0, add up to 6: twice the 3 edges.
Exercise · Put it in order: From edges to degrees. Arrange the lines into a function that builds an undirected graph from its edges as adjacency lists, and returns the degree of every vertex.
def degrees(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return [len(row) for row in adj]
adj = [[]] * nTo build a graph from a list of edges, make an empty list for every vertex, then add each edge at both ends.
Exercise · Break it: Counting a friend twice. This returns how many friends person v has in an undirected graph of n people. The list of pairs may name the same friendship twice, or in both orders, and each friend must count once. Find an input where it gives the wrong answer.
def friend_count(n, pairs, v):
adj = [[] for _ in range(n)]
for a, b in pairs:
adj[a].append(b)
adj[b].append(a)
return len(adj[v])Predict what happens
Q You build an undirected graph from the edges (0, 1), (1, 2) and (3, 4), with n = 6. How many vertices have an empty list?
Answer: C
Vertices 0 to 4 each appear in at least one edge. Vertex 5 appears in none, so its list stays empty. That is why you create a list for every vertex first.
Here is each operation side by side. Take n vertices, m edges, and call the degree of the vertex you ask about "deg".
| Operation | List of sets | List of lists | Matrix | What sets the cost |
|---|---|---|---|---|
| Add an edge | O(1): two set inserts | O(1): two appends, with no check for a repeat | O(1): two cell writes | One write for each direction |
| Is there an edge between u and v | O(1) on average: one lookup | O(deg of u): scan the list | O(1): read one cell | Whether you search or index |
| List the neighbours of u | O(deg of u) | O(deg of u) | O(n): read a whole row | The size of one list or one row |
| Degree of u | O(1): the size of the set | O(1): the length of the list | O(n): count a row | Whether the count is stored |
| Remove an edge | O(1) | O(deg of u): find it first | O(1) | Finding the entry |
| Memory | O(n + m) | O(n + m) | O(n squared) | Entries for edges, or cells for every pair |
| Build from m edges | O(n + m) | O(n + m) | O(n squared): the grid must be allocated | One pass over vertices and edges |
For most graphs in real programs, an adjacency list is the right default. Roads, friends and links between web pages all have far fewer edges than pairs of vertices.
Now drive a graph yourself, with vertices 0 to 6. Type two vertices, then add or remove an edge, or ask a question. Each operation runs step by step, with the graph on a ring and its adjacency list beside it. Switch on the matrix too if you like, and watch the counter of reads and writes.
Try these six, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a Graph class for the friend map of a chat app. You write five methods: add_edge, neighbors, degree, has_edge and vertex_count.
Three things to take care over:
add_edge puts each end in the other's set, so a friendship works in both directions. An edge from a person to themselves is ignored, and adding the same edge twice changes nothing.neighbors returns the friends of a person from the smallest id to the largest, so your answer matches the expected list. A person with no edges has no friends: return an empty list.degree of an unknown vertex is 0, and has_edge is false.Each test creates a new, empty graph, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a graph when the question is about links: who can reach whom, what is next to what, which things depend on which. Friends, roads, flights, links between web pages and the packages a program needs are all graphs.
Store it as an adjacency list when the graph has far fewer edges than pairs of vertices, which is almost always.
If the things sit in a regular grid, such as cells on a board, the grid already tells you the neighbours. Use row and column arithmetic, not a graph. If the links form a hierarchy with one parent each, use a tree. If you only look things up by key, use a hash map.
Use a matrix only for a small graph, or one where nearly every pair is joined.
In an undirected graph, an edge must be stored at both ends. If you add it to only one list, one person sees the friendship and the other does not.
adj[u].append(v) # only half the edge: v does not know about u
adj[v].append(u) # the line that is easy to forgetIn an undirected graph, store each edge at both ends. With only one end, a question from the other side gets the wrong answer.
A matrix for 100,000 vertices has ten billion cells, even when the graph has only a few hundred thousand edges. The program runs out of memory before it reads a single edge. Use an adjacency list.
grid = [[0] * n for _ in range(n)] # n = 100000: ten billion cellsMany inputs number vertices from 1 to n, while a list starts at index 0. Reading vertex n then fails with an index error. Either subtract 1 from every id, or make the list n + 1 long and ignore cell 0. Pick one way and keep it.
adj = [[] for _ in range(n)] # ids 0 to n - 1
adj = [[] for _ in range(n + 1)] # ids 1 to n: cell 0 is never usedThe input may list the same friendship twice, or list a pair in both orders. If you store lists, the degree comes out too big. A set per vertex ignores repeats. Check what the problem promises before you choose.
adj[u].append(v) # adds a repeat again and again
adj[u].add(v) # a set ignores a repeatA very popular vertex can have thousands of neighbours. A has-edge check that scans its list costs thousands of steps each time. If you ask that question often, keep a set for each vertex.
v in adj[u] # a list: scans every neighbour of u, O(degree)
v in adj[u] # a set: one lookup, O(1) on averageExplain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Vertices and edges
Q On a chat app you can follow an account without it following you back. Which graph models that?
Answer: B
A directed edge goes from one vertex to another and does not imply the way back. A matrix is a way to store a graph, not a kind of graph.
Checkpoint · Degree
Q1/2 An undirected graph has 5 edges. What is the sum of the degrees of all its vertices?
Answer: B
Each edge touches two vertices, so it adds one to two degrees. The sum is twice the number of edges: 10.
Q2/2 In a directed graph, vertex 4 has two edges leaving it and three arriving at it. What are its out-degree and in-degree?
Answer: B
The out-degree counts edges leaving the vertex, and the in-degree counts edges arriving at it.
Checkpoint · List and matrix
Q1/3 A graph has 1,000 vertices and 3,000 edges. Roughly how many entries does an undirected adjacency list hold, and how many cells does the matrix hold?
Answer: C
Each undirected edge is stored twice in a list, so 6,000 entries. A matrix always holds n times n cells, here one million.
Q2/3 Which storage answers "is there an edge between u and v?" with a single read, with no search?
Answer: B
A matrix reads cell (u, v). A list of lists must scan the list of u. A list of sets also answers in one lookup, on average.
Q3/3 You need the neighbours of one vertex in a graph of 100,000 vertices. Which costs less?
Answer: C
A list holds only the real neighbours, so it costs the degree. A matrix must read a whole row of n cells to find them.
Checkpoint · Building a graph
Q1/2 You build an undirected graph from a list of edges, and a vertex that no edge names has no list. What goes wrong?
Answer: B
Some vertices are isolated. If you only create lists while reading edges, an isolated vertex has none, so lookups for it fail.
Q2/2 For the undirected edge (2, 5), which two steps store it in an adjacency list?
Answer: B
An undirected edge works both ways, so each end needs the other in its list. With only one entry, a question from the other end gives the wrong answer.
Checkpoint · Choosing a storage
Q1/2 A graph of the roads in a maps app has about 10 million intersections, and each touches 3 or 4 roads. Which storage do you use?
Answer: B
A matrix would need 10 million times 10 million cells. A list holds about 40 million entries. Both can store weights, so weights do not decide it.
Q2/2 Input numbers the vertices from 1 to n, and you store the graph in an array that starts at index 0. What is a safe way to handle it?
Answer: B
Vertex n would be out of range in an array of length n. Convert the ids, or leave one spare cell, and use the same choice everywhere.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.