8.3Graph Applications
Shortest paths in an unweighted graph
How many stops do you pass between two stations on a metro map? How many friend steps lie between two people in a social network? In a graph where every edge is worth the same, that is an unweighted graph, the answer is the shortest path, and breadth-first search finds it. In this lesson you extend BFS so that it records the distance and the path of every vertex.
- Why BFS finds the vertices in order of their distance from the source
- How the path is recorded with the
distandprevarrays - How to read the path backwards from the target and print it from start to end
1Idea
BFS starts at the source and, thanks to the queue, finds all the vertices 1 step away first, then those 2 steps away, then those 3 steps away. So the moment a vertex is seen for the first time, the shortest path to it has been found: if there were a shorter path, the vertex would have been seen in an earlier wave.
The code differs from BFS in two arrays. dist[v] holds how many edges v is from the source; -1 means "not seen yet", so no separate visited array is needed. The distance of a newly seen neighbour is one more than the distance of the vertex that found it. prev[v] holds the vertex v was reached from.
The path itself sits backwards in the prev array: start at the target and follow prev and you reach the source. printPath turns it around with recursion: it prints the start of the path first, then the target. If the target cannot be reached, its distance stays -1; check that before printing the path.
This method is right only when all edges have the same length. If edges have different weights, for example roads given in kilometres, a path with few edges can be long. In a weighted graph the shortest path is found with Dijkstra's algorithm, which is one of the algorithms topics.
2Step by step
The drawing shows an undirected graph with 7 vertices; the source is 0. The d under a vertex is its distance. The orange vertex has just left the queue, and the orange edges are the new paths to the vertices found in that turn. The queue is shown under the drawing.
- Start. All distances are -1; the source 0 gets distance 0 and joins the queue.
- 0 leaves. Its neighbours 1 and 2 are seen for the first time: distance 1, previous vertex 0. Both join the queue.
- 1 leaves. 0 was seen already. 3 is new: distance 2, previous 1.
- 2 leaves. 0 and 3 were seen. 4 is new: distance 2, previous 2. 3 can also be reached in 2 steps through 2; the path found first stays.
- 3 leaves. 1 and 2 were seen. 5 is new: distance 3, previous 3.
- 4 leaves. 2 and 5 were seen; no new vertex. 5 can also be reached in 3 steps through 4; again the first one stays.
- 5 leaves. 6 is new: distance 4, previous 5.
- 6 leaves. No new neighbours and the queue is empty. Every vertex has its distance.
- The path to 6 is read backwards with
prev: 6, 5, 3, 1, 0.printPathturns it around and prints 0 1 3 5 6. Length 4.
#define MAX 8 struct Node { int data; struct Node* next;}; struct Graph { int n; bool directed; struct Node* adj[MAX];}; void shortestPath(struct Graph* g, int source, int dist[], int prev[]) { for (int u = 0; u < g->n; u++) { dist[u] = -1; prev[u] = -1; } int queue[MAX], front = 0, rear = 0; dist[source] = 0; queue[rear++] = source; while (front < rear) { int u = queue[front++]; for (struct Node* p = g->adj[u]; p != NULL; p = p->next) { int v = p->data; if (dist[v] == -1) { // seen for the first time: shortest dist[v] = dist[u] + 1; prev[v] = u; queue[rear++] = v; } } }} void printPath(int prev[], int target) { if (prev[target] != -1) // the start of the path first printPath(prev, prev[target]); printf("%d ", target);}class Node { int data; Node next; Node(int data) { this.data = data; }} class ListGraph { int n; boolean directed; Node[] adj; ListGraph(int n, boolean directed) { this.n = n; this.directed = directed; adj = new Node[n]; }} void shortestPath(ListGraph g, int source, int[] dist, int[] prev) { for (int u = 0; u < g.n; u++) { dist[u] = -1; prev[u] = -1; } java.util.ArrayDeque<Integer> queue = new java.util.ArrayDeque<>(); dist[source] = 0; queue.add(source); while (!queue.isEmpty()) { int u = queue.poll(); for (Node p = g.adj[u]; p != null; p = p.next) { int v = p.data; if (dist[v] == -1) { // seen for the first time: shortest dist[v] = dist[u] + 1; prev[v] = u; queue.add(v); } } }} void printPath(int[] prev, int target) { if (prev[target] != -1) // the start of the path first printPath(prev, prev[target]); System.out.print(target + " ");}from collections import deque class Node: def __init__(self, data): self.data = data self.next = None class ListGraph: def __init__(self, n, directed=False): self.n = n self.directed = directed self.adj = [None] * n def shortest_path(g, source, dist, prev): for u in range(g.n): dist[u] = -1 prev[u] = -1 dist[source] = 0 queue = deque([source]) while queue: u = queue.popleft() p = g.adj[u] while p is not None: v = p.data if dist[v] == -1: # seen for the first time: shortest dist[v] = dist[u] + 1 prev[v] = u queue.append(v) p = p.next def print_path(prev, target): if prev[target] != -1: # the start of the path first print_path(prev, prev[target]) print(target, end=" ")The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every vertex enters the queue once and every adjacency list is read once: O(V + E). Printing the path takes as long as the path, at most O(V).
dist, prev and the queue hold V elements.
One BFS gives the shortest paths from the source to all the vertices at once. Another target needs no new search; you just read the prev array from another vertex.
4Common mistake
A common mistake is using DFS instead of BFS:
// with DFS: the first path found may not be the shortestdist[v] = dist[u] + 1;DFS goes to the end of a branch; in the example it could go 0, 1, 3, 2 and think 2 is 3 steps away, while 2 is a neighbour of the source. Only BFS, which moves in waves, guarantees the shortest path. Another mistake is writing the distance when a vertex leaves the queue instead of when it joins: the same vertex can enter the queue twice and a longer path can be written.
5Try it
In the example graph, what would the distance of 6 be if the source were 2?
The answer is B. From 2 to 4 (1), from 4 to 5 (2), from 5 to 6 (3). There is no shorter path.
Show the answer
The answer is B. From 2 to 4 (1), from 4 to 5 (2), from 5 to 6 (3). There is no shorter path.
On a road map whose edges are weighted in kilometres, what can you say about the path BFS finds?
The answer is B. BFS keeps the number of edges as small as possible and ignores the weights. Two short roads can add up to fewer kilometres than one long road.
Show the answer
The answer is B. BFS keeps the number of edges as small as possible and ignores the weights. Two short roads can add up to fewer kilometres than one long road.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.