Introduction to graphs
easy 18 minA graph is a set of vertices joined by edges, directed or undirected, weighted or not.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
VERN: Vertices, Edges, Represent, Navigate. Name the dots, name the lines, store them as a list, walk them with a visited set.
A city map. Junctions are vertices, roads are edges, one-way streets are directed edges and the minutes to drive each road are weights. A tree is a city with exactly one route between any two junctions; a cycle is a loop you can drive round and come back to where you started.
Cheat sheet
- Graph
- G = (V, E)
- Handshake lemma
- sum of degrees = 2E
- Max edges
- V(V - 1)/2, or V(V - 1) directed
- Tree
- connected, acyclic, V - 1 edges
- Adjacency list
- O(V + E) space
- Adjacency matrix
- O(V²) space, O(1) edge check
- Neighbours
- list O(deg), matrix O(V)
- DFS / BFS
- O(V + E) with a visited set
- Fewest edges
- BFS; weighted needs Dijkstra
Spot it when you see
- Connections, friends, links, cables, roads, flights between things.
- "Depends on", "prerequisite", "must happen before": a directed graph, maybe a DAG.
- A grid of cells where you move up, down, left or right: an implicit graph.
- "How many groups" or "is everything connected": connected components.
- "Fewest steps" or "minimum moves": BFS on an unweighted graph.
- Input given as n and a list of pairs: build an adjacency list first.
Tricks that stick
- VERN: Vertices are the points, Edges the connections, Represent with a matrix or list, Navigate with BFS or DFS.
- Handshakes at a party: everyone's count adds up to twice the number of handshakes.
- Dense? Matrix. Sparse? List. And almost everything is sparse.
- Curly braces for undirected, round brackets for directed: {A, B} has no order, (A, B) does.
- Tree = graph minus cycles: V - 1 edges, one path between any two vertices.
- Graph traversal = tree traversal + a visited set + an outer loop for every component.
Do not forget
- Appending only one direction for an undirected edge.
- Traversing without a visited set, which loops forever on cycles.
- Starting one traversal from vertex 0 and missing other components.
- Leaving isolated vertices out of the adjacency dictionary.
- Building a V² matrix for a huge sparse graph.
- Quoting max edges as V²/2 instead of V(V - 1)/2.
- Using BFS for shortest paths when edges have weights.