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 nodes, numbered 0 to n - 1, and a list of edges, where an edge [a, b] joins node a and node b. The edges carry no lengths or costs, so every edge counts the same. Return the number of edges on the shortest path from node src to node dst, or -1 if no path joins them.

Example 1
Input: n = 6, edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[4,5]], src = 0, dst = 5
Output: 4
Explanation: 0 → 1 → 3 → 4 → 5.
Example 2
Input: n = 4, edges = [[0,1],[1,2]], src = 0, dst = 3
Output: -1
Explanation: Node 3 has no edges, so no path reaches it.
Solution

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 graph of Example 1 laid out by distance from node 0: node 0 at distance 0, nodes 1 and 2 at distance 1, node 3 at distance 2, node 4 at distance 3 and node 5 at distance 4. The edge from 2 to 3 is dashed because 3 was already found from 1. The shortest path 0, 1, 3, 4, 5 is highlighted in orange.

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 in teal, sits under distance 4, and 4 is the answer.

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, before it goes deeper. A queue keeps the rounds in order: newly found nodes join at the back, and the next node to look around from is taken off the front.

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] puts b in the list of a and a in the list of b, because an undirected edge can be walked either way. For Example 1 the lists are 0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2, 4], 4: [3, 5] and 5: [4].

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, dist, does two jobs. The value dist[v] is the number of edges from src to node v, and it starts at -1 for every node, meaning "not found yet". A neighbour whose value is no longer -1 has been found already and is skipped.

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 dst is taken off the queue, its distance is final. Nodes leave the queue in order of distance, so no shorter route to dst is still waiting. If src and dst are the same node, it is the first node taken off, with distance 0. If the queue runs empty first, dst was never found, and the answer is -1.

Java Solution

The method shortestPath works in these steps:

  1. First, build the adjacency list adj: one empty ArrayList per node, then, for each edge, add edge[1] to the list of edge[0] and edge[0] to the list of edge[1].
  2. Create the array dist with one entry per node, fill it with -1 using Arrays.fill, and set dist[src] to 0.
  3. Create queue, an ArrayDeque of node numbers, and add src to it.
  4. While the queue is not empty, take the front node u with poll(). If u is dst, return dist[u].
  5. Otherwise, an inner loop goes over each neighbour v in the list of u. A neighbour whose dist[v] is still -1 gets dist[u] + 1 and joins the back of the queue.
  6. If the queue runs empty without reaching dst, return -1.

The main method runs both examples, Example 1 backwards from 5 to 0, a search whose src and dst are both node 2, a search from 1 to 2, and a graph of one node with no edges.

Java
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:

Output
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 src and dst, so it is returned as soon as it is taken off.

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 n, and E is the number of edges in edges.

  • 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 dist and the queue each hold at most V nodes.

When the edges have different lengths, fewest edges no longer means shortest, and Dijkstra's Algorithm takes over.