← capítulo

Graph representations

Vertices + edges. No root, cycles allowed. How you store it sets the cost of everything after.

Two representations, mirror-image costs

Adjacency listAdjacency matrix
SpaceO(V+E)O(V²)
has_edgeO(degree)O(1)
neighborsO(degree)O(V)
Best forsparse (most)dense / edge tests

Watch a graph get built

Each edge appends to both endpoints' neighbor lists.

Real graphs are sparse → list wins

Sparse graph, 4000 vertices: 437 KB (list) vs 125 MB (matrix) → 286×. Matrix also makes every traversal O(V²) instead of O(V+E).

Also: directed/undirected, weighted

Takeaway

Default to the adjacency list — real graphs are sparse. Every algorithm ahead is O(V+E) because of it. Next: BFS and DFS.