Graph Basics
A graph models things and their connections: vertices (nodes) joined by edges. They represent road maps, social networks, and dependency chains.
Edges can be directed (one-way) or undirected (mutual), and may carry a weight representing distance, cost, or capacity.
| Property | Description |
|---|---|
| Vertices () | The nodes being connected |
| Edges () | The connections between nodes |
| Weight | Cost, distance, or capacity |
Common Pitfall: Using an adjacency matrix for a large sparse graph. A million-node graph with few edges wastes space on empty cells.
Memory Trade-offs
Choosing a graph representation is a classic space-time trade-off between two standard structures.
An adjacency matrix is a grid where entry records the connection. It allows edge checking, suiting dense graphs.
An adjacency list stores each vertex's neighbors. It uses space, suiting sparse graphs.
| Representation | Space | Check edge | Best for |
|---|---|---|---|
| Adjacency matrix | Dense graphs | ||
| Adjacency list | Sparse graphs |