Module 9 · Graphs and Tries · Lesson 29 of 40
Graphs: things and connections
Vertices and edges, directed and weighted graphs, and how to store a graph with an adjacency list.
In this lesson · about 20 minutes
- Use the words vertex, edge, neighbour, directed and weighted
- Store a graph as an adjacency list (a dict of lists)
- Compare an adjacency list with an adjacency matrix
A graph is a set of things and the connections between them. Cities and roads. People and friendships. Web pages and links. Trees are graphs too, just without loops.
| Word | Meaning |
|---|---|
| Vertex (or node) | One thing: a city, a person |
| Edge | A connection between two vertices |
| Neighbours | Vertices joined directly by an edge |
| Degree | How many edges touch a vertex |
| Path | A route from one vertex to another along edges |
| Cycle | A path that comes back to where it started |
| Connected | Every vertex can reach every other one |
We write V for the number of vertices and E for the number of edges.
Kinds of graphs
- Undirected: edges go both ways (friendship).
- Directed: edges have arrows, one way only (following someone online, a one-way street).
- Weighted: each edge has a number, like a distance or a cost.
- Unweighted: every edge counts the same.
Storing a graph
The most common way is an adjacency list: a dict where each vertex maps to a list of its neighbours.
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C"],
}
The other way is an adjacency matrix: a V × V grid where matrix[i][j] is 1 if there is an edge from i to j.
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Memory | O(V + E) | O(V²) |
| "Is there an edge A–B?" | O(degree) | O(1) |
| List all neighbours | O(degree) | O(V) |
| Best for | Most real graphs (few edges) | Small graphs with many edges |
Try it: build a graph from a list of edges
Exercise
Build a directed graph
Write build(edges) that turns a list of directed edges (from, to) into an adjacency list dict. Every vertex that appears anywhere should be a key, even if it has no outgoing edges (give it an empty list).
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.