Adjacency lists and adjacency matrices
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
The Software lesson "Graphs" shows that a graph can be stored as an adjacency list or an adjacency matrix. This lesson measures the difference. Build both from the same edge list of a 5-vertex directed graph, then ask each the same questions and count the reads: one for an edge check in the matrix, up to deg(u) in the list, V + E against V² to visit every edge. The Software lesson "Graph search: BFS and DFS" and the Maths lesson on graph theory supply the walks and the vocabulary used here.
One graph, two shapes
A directed graph: 5 vertices numbered 0 to 4 and 6 one-way edges, such as 3 → 4. Python receives it as an edge list of pairs. Algorithms need a shape they can ask questions of quickly: a list per vertex, or a grid.
edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1), (3, 4)] V = 5, E = 6 out-degree deg(u) = edges leaving u: deg(0) = 2 deg(1) = 1 deg(2) = 1 deg(3) = 2 deg(4) = 0 sum of out-degrees = 6 = E
اقرأ الدرس خطوة بخطوة
One graph, two shapes
A directed graph: 5 vertices numbered 0 to 4 and 6 one-way edges, such as 3 → 4. Python receives it as an edge list of pairs. Algorithms need a shape they can ask questions of quickly: a list per vertex, or a grid.
edges = [(0, 1), (0, 2), (1, 2), (2, 3), (3, 1), (3, 4)] V = 5, E = 6 out-degree deg(u) = edges leaving u: deg(0) = 2 deg(1) = 1 deg(2) = 1 deg(3) = 2 deg(4) = 0 sum of out-degrees = 6 = EBuild the adjacency list
Start with one empty Python list per vertex. For each edge (u, v), append v to adj[u]. Six edges, six appends: adj[3] ends up as [1, 4]. Each directed edge is stored once, in the list of the vertex it leaves.
adj = [[] for _ in range(V)] for u, v in edges: adj[u].append(v) # amortised O(1) adj[0] = [1, 2] adj[1] = [2] adj[2] = [3] adj[3] = [1, 4] adj[4] = []Build the adjacency matrix
The matrix starts as a 5 × 5 grid of zeros: 25 cells, made before any edge is read. Then each edge (u, v) sets mat[u][v] = 1. Row u shows where u’s edges go; column v shows where v’s edges come from.
mat = [[0] * V for _ in range(V)] for u, v in edges: mat[u][v] = 1 col 0 1 2 3 4 row 0 0 1 1 0 0 row 1 0 0 1 0 0 row 2 0 0 0 1 0 row 3 0 1 0 0 1 row 4 0 0 0 0 0Count the space
The list holds 5 heads plus 6 entries: V + E = 11 slots. The matrix holds V × V = 25 cells, even with no edges. Lists grow with the edges; the matrix grows with the square of the vertices.
list: V + E = 5 + 6 = 11 slots Θ(V + E) matrix: V × V = 5 × 5 = 25 cells Θ(V²) cells holding 1: 6 of 25Edge check: the matrix
Ask: is there an edge from 3 to 4? The matrix goes straight to row 3, column 4 and reads one cell. It holds 1, so yes. One read, however big the graph: O(1) time.
>>> mat[3][4] == 1 True reads: 1 (index row, index column) time: O(1)Edge check: the list
The list must search. Python’s in walks adj[3] from the left: 1, no; 4, yes. That took 2 reads. At worst it reads every entry, so the cost is O(deg(u)), where deg(u) counts the edges leaving u.
>>> 4 in adj[3] True adj[3] = [1, 4] read slot 0: 1 no read slot 1: 4 yes, stop reads: 2 time: O(deg(3)) = O(2)Where does 3 lead?
Now list every vertex 3 points to. The list hands over adj[3] = [1, 4]: 2 reads. The matrix must read all 5 cells of row 3 to find its two 1s. That is O(deg(u)) against O(V).
>>> adj[3] [1, 4] >>> [v for v in range(V) if mat[3][v]] [1, 4] list reads: 2 O(deg(u)) matrix reads: 5 O(V) row 3 = 0 1 0 0 1Visit every edge
BFS and DFS ask that question for every vertex. With lists that is 5 heads plus 6 entries: 11 reads, O(V + E). With the matrix it is every cell: 25 reads, O(V²), even when most cells are 0.
for u in range(V): for v in adj[u]: ... # list for u in range(V): for v in range(V): if mat[u][v]: ... # matrix list: V + E = 11 reads Θ(V + E) matrix: V² = 25 reads Θ(V²)Sparse or dense?
Pick by density. A graph with 1,000 vertices and 3,000 edges needs a 1,000,000-cell matrix that is almost all zeros, but only 4,000 list slots. When E is close to V², or edge checks dominate, choose the matrix.
V = 1,000, E = 3,000 list: V + E = 4,000 slots matrix: V² = 1,000,000 cells (0.3% hold a 1) sparse (E much less than V²): adjacency lists dense (E close to V²), many edge checks: matrix
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A directed graph has V = 5 vertices and E = 6 edges. How many slots do its adjacency lists hold, counting one head per vertex, and how many cells does its adjacency matrix hold?
Lists: one head per vertex plus one entry per directed edge, V + E = 11. Matrix: one cell per ordered pair of vertices, V × V = 25, whether or not an edge exists.
02Which question does an adjacency matrix answer in O(1) time?
mat[u][v] is one indexed read. Listing u's neighbours needs the whole row (V reads), and counting or visiting every edge needs every cell (V² reads).
03adj[3] is [1, 4]. How many entries does the Python expression 0 in adj[3] read?
in scans the list from the left and stops at a match. 0 is not there, so it reads both entries before answering False: a miss costs deg(u) reads.
04BFS on a graph with V vertices and E edges looks at every neighbour of every vertex. What is that cost with adjacency lists and with a matrix?
Lists hand over each vertex's neighbours directly: V heads plus E entries. The matrix must read all V cells of every row, V² in total, even where the cells are 0.
05Why is mat = [[0] * V] * V a bug?
Multiplying a list copies references, not the inner list (Python FAQ). Use [[0] * V for _ in range(V)], which makes a new row each time round.
المسرد
- Adjacency list
- For each vertex, a list of the vertices its edges lead to. adj[u] holds u's neighbours.
- Adjacency matrix
- A V × V grid of 0s and 1s. mat[u][v] is 1 when there is an edge from u to v.
- Directed graph
- A graph whose edges have a direction: u → v does not imply v → u.
- Out-degree, deg(u)
- The number of edges leaving vertex u. It is the length of adj[u].
- Sparse graph
- A graph with far fewer edges than V², the most it could have. Most real graphs are sparse.
- Dense graph
- A graph whose edge count is close to V².
- Θ(V + E)
- Cost that grows in proportion to the size of the graph: its vertices plus its edges. Often called linear time for graph algorithms.
الملاحظات والمصادر
- The figure counts slots and cells, not bytes. A Python list of lists also stores pointers and spare room for appends, but the growth stays the same: Θ(V + E) for lists and Θ(V²) for the matrix.
- In an undirected graph every edge is stored twice, as v in adj[u] and u in adj[v], so the lists hold V + 2E slots, and the matrix is symmetric about its diagonal.
- Storing each adj[u] as a Python set instead of a list makes “is v a neighbour of u?” O(1) on average while keeping Θ(V + E) space. MIT 6.006 mentions the same trick with a hash table per vertex.
- Build the matrix with [[0] * V for _ in range(V)]. The shortcut [[0] * V] * V makes V references to one row, so setting mat[3][4] would change every row (Python FAQ).
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 9: Breadth-First Search (graph representations)
- Sedgewick and Wayne, Algorithms 4th ed., §4.1 Undirected Graphs
- Sedgewick and Wayne, Algorithms 4th ed., §4.2 Directed Graphs
- P. Morin, Open Data Structures (Python), §12.1 AdjacencyMatrix
- P. Morin, Open Data Structures (Python), §12.2 AdjacencyLists
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §20.1 Representations of graphs
- Python documentation: Time complexity of built-in types
- Python FAQ: How do I create a multidimensional list?
اختبار يتاح بعد الخطوة الأخيرة.