πΈοΈ
Graphs (Basic)
Adjacency list / matrix Β· directed / weighted
13. Graph Representation
Choose the right graph representation based on density and required operations. Master the standard idioms for reading graph input from BOJ-style problems.
graphadjacency listadjacency matrix
Duration
β± ~45 minutes
Level
π Intermediate
Prerequisite
π― Basics track
OUTCOME
Convert any graph input format into a usable data structure in 5 lines.
What you'll learn
- 1Choose between adjacency list and adjacency matrix
- 2Handle directed, undirected, weighted edges
- 3Read BOJ-style graph input quickly
Overview
Most graph algorithms work with either an adjacency list or an adjacency matrix. The list is space-efficient (O(V + E)); the matrix gives O(1) edge lookup but uses O(VΒ²) space. For competitive programming, adjacency list is the default.
Core Concepts
1. Adjacency list
python
n = 5
adj = [[] for _ in range(n + 1)] # 1-indexed nodes
edges = [(1, 2), (1, 3), (2, 4), (3, 5)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u) # remove this line for directed graphs
# Neighbors of node 1
for neighbor in adj[1]:
... # O(degree)2. Adjacency matrix
python
n = 5
mat = [[0] * (n + 1) for _ in range(n + 1)]
edges = [(1, 2), (1, 3)]
for u, v in edges:
mat[u][v] = 1
mat[v][u] = 1
# Is there an edge u-v?
mat[u][v] # O(1)3. Weighted graphs
python
# adjacency list with weights
adj = [[] for _ in range(n + 1)]
for u, v, w in weighted_edges:
adj[u].append((v, w))
adj[v].append((u, w))
for next_v, weight in adj[u]:
...4. Comparison
| Adjacency list | Adjacency matrix | |
|---|---|---|
| Space | O(V + E) | O(VΒ²) |
| Edge lookup | O(degree) | O(1) |
| Iterate neighbors | O(degree) | O(V) |
| Good for | Sparse graphs (most cases) | Dense graphs / Floyd-Warshall |
Examples
Example 1 β src/01_adj_list.py
Build adjacency list from BOJ-format input, print all edges.
Example 2 β src/02_adj_matrix.py
Adjacency matrix with O(1) edge query.
Example 3 β src/03_weighted.py
Adjacency list with weights β needed for Dijkstra.
Example 4 β src/04_grid_as_graph.py
Treat a 2D grid as a graph with 4-directional movement (BFS/DFS staple).
Common Mistakes
- Forgetting to add both directions for an undirected graph.
- Using 0-indexed `adj = [[] for _ in range(n)]` when input is 1-indexed β IndexError or off-by-one.
- Choosing a matrix when V > 1000 β runs out of memory.
- Inserting duplicate edges silently when input contains parallel edges.
Recap
- Adjacency list is the default for sparse graphs.
- Adjacency matrix is reserved for dense graphs (V β€ 500) or Floyd-Warshall.
- Weighted edges β use tuples in the adjacency list.
Try It
- BOJ 1260 (DFS and BFS) β read graph, run both.
- Build the adjacency list, then for each node print its neighbors.
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β