8.1Graph with an Adjacency Matrix
Breadth-first search (BFS)
Walking a graph means visiting every vertex reachable from a start vertex exactly once. Breadth-first search (BFS) does it layer by layer: first the neighbours of the start, then their neighbours not seen yet. It is the same as level-order traversal in a tree, with one difference: a graph has cycles, so you can arrive at a vertex a second time, and a visited array prevents that.
- Why BFS with a queue hands out the vertices layer by layer
- Why the visited array is a must in a graph with cycles
- Why BFS with a matrix takes O(n²) time
1The idea
The start vertex is marked and put into the queue. On each turn of the loop the front vertex u is taken out and printed. Then the row of u is walked: every v that is a neighbour and not marked yet is marked and added to the back of the queue. When the queue is empty, every vertex reachable from the start has been printed.
A vertex is marked as it joins the queue, not as it leaves. That way a vertex enters the queue at most once. If the mark were set on leaving, a vertex found from two different neighbours would enter the queue twice and be printed twice. In the example 4 is a neighbour of both 1 and 3; it is marked when found from 1 and is not added again when 3's turn comes.
The first in, first out order of the queue decides the order: all vertices 1 edge away from the start leave before those 2 edges away. That is why BFS also finds how to reach each vertex with the fewest edges in an unweighted graph; the shortest path lesson uses this. The neighbours are walked from the smallest number up, so vertices at the same distance also come out from smallest to largest.
| Distance | Vertices |
|---|---|
| 0 | 0 |
| 1 | 1, 3 |
| 2 | 2, 4 |
| 3 | 5 |
If the graph is not connected, BFS only walks the piece of the start vertex. To walk the whole graph, BFS is started again from every vertex that is still unmarked; the connected components lesson does this.
2Step by step
The drawing walks the sample graph with BFS starting at 0. Faded vertices have not been found yet; u is the vertex just taken out of the queue (orange), the green ones were printed earlier. Orange edges are the ones through which a new vertex was found. The queue is shown under the drawing.
- Start: no vertex is marked.
bfs(&g, 0)is called. - 0 is marked and put into the queue. Queue: 0.
- 0 is taken out and printed. Row 0 holds 1 and 3; both are marked and join the queue. Output: 0.
- 1 is taken out and printed. Row 1 holds 0, 2 and 4. 0 is marked; 2 and 4 join the queue. Output: 0 1.
- 3 is taken out and printed. Its neighbours 0 and 4 are already marked; nothing joins the queue. Output: 0 1 3.
- 2 is taken out and printed. Its neighbour 5 is seen for the first time and joins the queue. Output: 0 1 3 2.
- 4 is taken out and printed. Its neighbours 1, 3 and 5 are marked. Output: 0 1 3 2 4.
- 5 is taken out and printed. The queue is empty and the loop ends. Output: 0 1 3 2 4 5.
- BFS order: 0, then 1 and 3 at distance 1, then 2 and 4 at distance 2, and 5 last. The orange edges formed a BFS tree.
#define MAX 8 struct Graph { int n; bool directed; int adj[MAX][MAX];}; void bfs(struct Graph* g, int start) { bool visited[MAX] = {false}; int queue[MAX]; int front = 0, rear = 0; visited[start] = true; // mark it as it joins the queue queue[rear++] = start; while (front < rear) { int u = queue[front++]; // take the front one printf("%d ", u); for (int v = 0; v < g->n; v++) { if (g->adj[u][v] == 1 && !visited[v]) { visited[v] = true; queue[rear++] = v; // the neighbour goes to the back } } }}class MatrixGraph { int n; boolean directed; int[][] adj; MatrixGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new int[n][n]; } void bfs(int start) { boolean[] visited = new boolean[n]; java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>(); visited[start] = true; // mark it as it joins the queue queue.add(start); while (!queue.isEmpty()) { int u = queue.poll(); // take the front one System.out.print(u + " "); for (int v = 0; v < n; v++) { if (adj[u][v] == 1 && !visited[v]) { visited[v] = true; queue.add(v); // the neighbour goes to the back } } } }}from collections import deque class MatrixGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [[0] * n for _ in range(n)] def bfs(self, start): visited = [False] * self.n visited[start] = True # mark it as it joins the queue queue = deque([start]) while queue: u = queue.popleft() # take the front one print(u, end=" ") for v in range(self.n): if self.adj[u][v] == 1 and not visited[v]: visited[v] = True queue.append(v) # the neighbour goes to the backThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every vertex leaves the queue once, and when it does, the n cells of its row are walked: n × n.
The visited array and the queue hold at most n elements.
Every row is scanned from start to end even when there are few edges. BFS with adjacency lists looks only at the edges that exist and takes O(n + e).
4Common mistake
The most common mistake is marking a vertex as it leaves the queue:
int u = queue[front++];visited[u] = true; // too latefor (int v = 0; v < g->n; v++) if (g->adj[u][v] == 1 && !visited[v]) queue[rear++] = v;In the example 4 is a neighbour of both 1 and 3. When 1 leaves, 4 joins the queue but is not marked; when 3 leaves, 4 is still unmarked, so it joins again and is printed twice. In C the queue of size MAX can overflow too. Never marking at all is worse: in a graph with a cycle, 0 and 1 keep adding each other to the queue forever.
5Try it
If BFS starts at vertex 3 of the sample graph, what is the output?
The answer is A. The neighbours of 3 are 0 and 4 (smallest first). When 0 leaves, 1 is added; when 4 leaves, 5 is added. When 1 leaves, 2 is added. Order: 3 0 4 1 5 2.
Show the answer
The answer is A. The neighbours of 3 are 0 and 4 (smallest first). When 0 leaves, 1 is added; when 4 leaves, 5 is added. When 1 leaves, 2 is added. Order: 3 0 4 1 5 2.
Why is a vertex marked in BFS as it joins the queue?
The answer is B. A vertex found from two neighbours would be added to the queue twice, and printed twice, if it were not marked when it joins.
Show the answer
The answer is B. A vertex found from two neighbours would be added to the queue twice, and printed twice, if it were not marked when it joins.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.