Graphs: vertices, edges, directed and weighted
1 A city map is a graph
In a tree, each node has exactly one parent, and nothing loops back. A city's roads follow no such rule. A junction can have five roads, and we can drive round a block back to where we started. Here is a small city:
This map is a graph. Each junction is a vertex (also called a node), and each road is an edge between two vertices. We write V for the number of vertices and E for the number of edges. This map has V = 7 and E = 6. Problems usually call them n and m.
Questions about the map become questions about the graph. Can we drive from 0 to 4? Which junctions are cut off? Friendships, flights and web links are graphs too.
2 The words for a graph
Graph problems use a few words, all shown here on our map:
- Neighbours. Two vertices joined by an edge are adjacent, and each is a neighbour of the other. The neighbours of 1 are 0, 2 and 3.
- Degree. The number of edges at a vertex. Vertex 1 has degree 3, and vertex 4 has degree 1.
- Path. A walk from vertex to vertex along edges, such as 0, 1, 3, 4. Its length is the number of edges, here 3.
- Cycle. A path that comes back to its start without reusing an edge, such as 0, 1, 2, 0.
- Connected. Two vertices are connected when some path joins them. A connected component is a group in which every vertex reaches every other, and nothing outside. Our map has two: the mainland 0 to 4, and the island 5 and 6.
A self-loop is an edge from a vertex to itself, and parallel edges are two edges between the same pair. Most problems rule both out, but not all.
3 One-way streets and road lengths
On our map, every road goes both ways. That is an undirected graph, like a friendship: if Asha is Ravi's friend, Ravi is Asha's friend.
A follow on a social app is one-way, like a one-way street. A graph where each edge has a direction is a directed graph. Its edges are arrows, from u to v. Here are the same six pairs, read both ways:
In the directed map, we can drive 0 → 1 → 3 → 4, but no street leads out of 4. So 0 reaches 4, and 4 does not reach 0.
A vertex now has two degrees. Its in-degree counts the arrows coming in, and its out-degree counts the arrows going out:
| Vertex | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| in-degree | 1 | 1 | 1 | 1 | 1 | 0 | 1 |
| out-degree | 1 | 2 | 1 | 1 | 0 | 1 | 0 |
Nothing leads into vertex 5, and vertex 4 is a dead end.
A road also has a length. When each edge carries a number, the graph is weighted. The number can be kilometres, minutes or a price:
The fewest roads is not always the shortest drive, and later lessons find the shortest one. In an unweighted graph, every edge counts 1. A graph can be both directed and weighted, like one-way flights with prices.
4 Trees, DAGs and other shapes
A few shapes of graph come up again and again:
- Tree. A connected graph with no cycle. With n vertices, it always has n − 1 edges. The trees topic used this shape, with one vertex picked as the root. One more edge makes a cycle, and one edge fewer splits it in two.
- DAG. A directed acyclic graph has arrows and no cycle along them. Tasks with an order form one: socks come before shoes.
- Bipartite. The vertices split into two sides, and every edge joins one side to the other. Students and the clubs they joined form one.
A graph with several components and no cycle is a forest: a group of trees.
5 How problems give a graph
A problem rarely draws its graph. It hands it over in one of four forms:
| Form | What we get | Example |
|---|---|---|
| n and an edge list | n = 7, edges = [[0,1], [1,2], …] | BFS and DFS of a Graph |
| Adjacency list | graph[i] lists the neighbours of i | Keys and Rooms |
| Grid | grid[r][c], each cell a vertex | Number of Islands |
| Implicit | a rule that says which pairs join | Word Ladder |
In Keys and Rooms, rooms[i] lists the keys in room i. Each key is an arrow from room i to the room it opens, so rooms is a directed graph. In All Paths From Source to Target, graph[i] lists the arrows out of i in a DAG.
A grid is a graph in disguise. Each cell is a vertex, joined to the cells above, below, left and right:
An implicit graph is never written down. In a word puzzle, each word is a vertex, and two words join when they differ in one letter:
Turning cat into dog one letter at a time is a path in this graph. The code works out each word's neighbours when it needs them.
Some problems number the vertices from 0 to n − 1, and some from 1 to n. The constraints say which: 0 ≤ u < n or 1 ≤ u ≤ n.
6 Degrees, and counting them
Here is our map again, with each vertex's degree beside it:
The degrees add up to 2 + 3 + 2 + 2 + 1 + 1 + 1 = 12, twice the 6 roads. Each road has two ends, and each end adds 1 to the degree of the vertex it touches. So for any undirected graph:
This is the handshake lemma: every handshake at a party involves two hands. In a directed graph, each arrow has one tail and one head, so the in-degrees add up to E, and so do the out-degrees.
The same idea is the code. We start every degree at 0 and go through the edge list once. Each edge [u, v] adds 1 at u and 1 at v:
| Edge | degree after it |
|---|---|
| start | [0, 0, 0, 0, 0, 0, 0] |
| [0, 1] | [1, 1, 0, 0, 0, 0, 0] |
| [1, 2] | [1, 2, 1, 0, 0, 0, 0] |
| [2, 0] | [2, 2, 2, 0, 0, 0, 0] |
| [1, 3] | [2, 3, 2, 1, 0, 0, 0] |
| [3, 4] | [2, 3, 2, 2, 1, 0, 0] |
| [5, 6] | [2, 3, 2, 2, 1, 1, 1] |
For a directed graph, each arrow [u, v] adds 1 to the in-degree of v alone.
On our map, countDegrees gives [2, 3, 2, 2, 1, 1, 1]. On the same pairs read as arrows, countInDegrees gives [1, 1, 1, 1, 1, 0, 1], the row from section 3. Out-degrees are the same loop with u in place of v.
C++
Start at 0. vector<int> degree(n, 0) fills every count with 0. A plain array declared inside a function starts with garbage instead.
Already 0. new int[n] fills every count with 0, so the loop can add straight away.
Unpacking. for u, v in edges takes each pair apart. In the in-degree loop, _ marks the part we do not use.
Do not forget fill(0). new Array(n) alone holds empty places, and ++ on an empty place gives NaN.
Already 0. make([]int, n) fills every count with 0, so the loop can add straight away.
Indexes are usize. The vertices arrive as i32, so as usize converts each one before it indexes the vector.
Already 0. new int[n] fills every count with 0, so the loop can add straight away.
Cost. Making the array takes O(V), and the loop does O(1) work per edge, so the whole count is O(V + E) time. The array takes O(V) space.
7 How big a graph gets
Each of V vertices can join the V − 1 others. That counts every edge from both ends, so a graph has at most V(V − 1) / 2 edges. A graph near that limit is dense. A graph with a few edges per vertex is sparse:
Most problem graphs are sparse, as a city's junctions have a few roads each. At V = 10⁵, a graph could have about 5 × 10⁹ edges. A typical problem gives at most 2 × 10⁵.
So graph code must never try every pair of vertices. At V = 10⁵ that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE). Good graph code looks at each vertex once, and at each vertex's edges. By the handshake lemma, that is V + 2E steps, a few times 10⁵. We write it O(V + E):
BFS and DFS cost O(V + E) too. The size also decides how we store a graph. A table of every pair needs V² places, about 10¹⁰ here. A list of each vertex's neighbours needs about V + 2E. The next lesson compares the two.
8 Mistakes, and what comes next
- One direction of an undirected edge. Each
[u, v]must count at both ends. Counting only at u gives vertex 4 degree 0, as if the road from 3 did not exist. - 1-based input in a 0-based array. Numbered from 1, our island road is
[6, 7]. It writes to index 7 of an array of size 7, a Runtime Error. Make the array size n + 1, or subtract 1 from each vertex. - Assuming the graph is connected. A search from vertex 0 never reaches 5 or 6. To visit every vertex, the code starts a new search at each vertex not yet seen.
- Assuming no self-loops or repeated edges. If
[0, 1]comes twice, vertex 0 gets degree 3 with only two neighbours. Read the constraints before trusting a degree.
This subtopic's problems store a graph and visit every vertex. The next lesson stores it, as an adjacency list or an adjacency matrix. The one after it, BFS and DFS on a graph, visits every vertex, as level order did on a tree.
Before writing graph code, read the input line by line: directed or not, weighted or not, numbered from 0 or from 1, and whether it can have more than one component.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.