Shortest Path in Unweighted Graph (BFS)
Count the fewest edges between two nodes of an unweighted graph with breadth-first search.
An undirected graph has n[a, b]srcdst
Example 1
Output: 4
Explanation: 0 → 1 → 3 → 4 → 5.
Example 2
Output: -1
Explanation: Node 3 has no edges, so no path reaches it.
The Idea
Picture a small rail network where every hop between two neighbouring stations takes the same time. The fastest trip is then the one with the fewest hops. A graph like this, whose edges have no length or cost attached, is called unweighted, and its shortest path is the path with the fewest edges.
Walk through Example 1. Node 0 is joined to 1 and to 2, both 1 and 2 are joined to 3, and a chain runs on from 3 to 4 to 5. Two routes lead from 0 to 3, one through 1 and one through 2, and each takes two edges. How do we find the fewest edges to 5 without listing every route?
Spread out from 0 in rounds. Round one looks one edge away from 0 and finds 1 and 2. Round two looks one edge away from those and finds 3. Each node found in a round is one edge farther from 0 than the nodes of the round before, so the round in which a node is first found is its distance.
The picture lays Example 1 out in those rounds. Each grey column, headed distance 0 to distance 4, holds the nodes first found in that round. Node 3 sits under distance 2 because node 1 reaches it first. The dashed edge from 2, marked "3 already found", leads to a node that already has its distance, so it adds nothing.
The orange line is the shortest path 0 → 1 → 3 → 4 → 5. Node 5, the dst
Searching in rounds like this, finishing every node at one distance before touching any node at the next, is called breadth-first search, or BFS. It covers the graph's breadth, the nodes near src
Solution Approach
Four decisions shape the code: how the edges are stored, how distances and visited nodes are tracked, when a node is marked, and when the search can stop.
Storing the edges
How does the search find a node's neighbours quickly? The edge list is turned into an adjacency list: for each node, a list of the nodes joined to it. An edge [a, b]
Storing each edge only one way is a real trap. The lists then only allow the walk from a to b. On Example 1, a search from 0 to 5 still returns 4, because every edge happens to lead away from 0. From 5 to 0 it returns -1, even though the same four edges join them.
Distances and visited nodes
What stops the search from going round in circles, from 0 to 1 and back to 0? One array, distdist[v]src
When a node is marked
Should a node get its distance when it joins the queue, or when it is taken off? When it joins. Then each node enters the queue once: on Example 1, the queue receives 6 entries, one per node.
Marking a node only when it is taken off still gives 4 on Example 1, but node 3 now joins the queue twice. It is added from 1 and again from 2, before either copy is taken off, so the queue receives 7 entries instead of 6. Every extra copy is extra work that changes nothing.
When to stop
When can the search stop? When dstdstsrcdstdst
Java Solution
The method shortestPath
- First, build the adjacency list
: one emptyadj per node, then, for eachArrayList , addedge to the list ofedge[1] andedge[0] to the list ofedge[0] .edge[1] - Create the array
with one entry per node, fill it with -1 usingdist , and setArrays.fill to 0.dist[src] - Create
, anqueue of node numbers, and addArrayDeque to it.src - While the queue is not empty, take the front node
withu . Ifpoll() isu , returndst .dist[u] - Otherwise, an inner loop goes over each neighbour
in the list ofv . A neighbour whoseu is still -1 getsdist[v] and joins the back of the queue.dist[u] + 1 - If the queue runs empty without reaching
, return -1.dst
The mainsrcdst
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
public class ShortestPathBFS {
public static int shortestPath(int n, int[][] edges, int src, int dst) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]); // an undirected edge goes both ways
adj.get(edge[1]).add(edge[0]);
}
int[] dist = new int[n];
Arrays.fill(dist, -1); // -1 also means "not found yet"
dist[src] = 0;
Deque<Integer> queue = new ArrayDeque<>();
queue.add(src);
while (!queue.isEmpty()) {
int u = queue.poll();
if (u == dst) {
return dist[u]; // nodes leave in order of distance
}
for (int v : adj.get(u)) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1; // mark it the moment it is queued
queue.add(v);
}
}
}
return -1;
}
public static void main(String[] args) {
int[][] edges1 = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}};
int[][] edges2 = {{0, 1}, {1, 2}};
System.out.println(shortestPath(6, edges1, 0, 5));
System.out.println(shortestPath(4, edges2, 0, 3));
System.out.println(shortestPath(6, edges1, 5, 0));
System.out.println(shortestPath(6, edges1, 2, 2));
System.out.println(shortestPath(6, edges1, 1, 2));
System.out.println(shortestPath(1, new int[0][], 0, 0));
}
}
Running it prints:
4
-1
4
0
2
0
The 4 on top is Example 1, the four edges of 0 → 1 → 3 → 4 → 5. Below it, -1 answers Example 2: node 3 has no edges, so it never joins the queue and the queue runs empty.
The third line runs Example 1 backwards, from 5 to 0, and also gets 4. With each edge stored one way only, this same search returns -1. The 0 on the fourth line comes from node 2 being both srcdst
The 2 on the fifth line goes from 1 to 2. They share no edge, so the path runs through 0 or through 3, two edges either way. The last 0 is a graph of a single node and no edges, where the start is already the goal.
Complexity
The cost depends on the size of the graph: V is the number of nodes, which the code calls nedges
- Time: O(V + E), because building the lists reads each of the E edges once, and each of the V nodes leaves the queue at most once, so its list entries are checked once.
- Space: O(V + E), because the adjacency lists hold 2E entries, while
and the queue each hold at most V nodes.dist
When the edges have different lengths, fewest edges no longer means shortest, and