Graph - Breadth First Search (BFS)

Visit every node a start node can reach in a graph, nearest nodes first, with the help of a queue.

A graph has n nodes, numbered 0 to n - 1, and a list of undirected edges. An edge {a, b} joins node a and node b, and it can be followed both ways. Given the graph and a node start, list the nodes in the order breadth-first search (BFS) reaches them.

Breadth-first search visits start first, then every node one edge away from it, then every node two edges away, and so on. Among the neighbours of one node (the nodes an edge joins it to), take them in the order their edges appear in the list. Nodes that cannot be reached from start are left out.

Example 1
Input: n = 7, edges = [[0, 1], [0, 2], [1, 3], [1, 4], [2, 4], [3, 5], [4, 5]], start = 0
Output: [0, 1, 2, 3, 4, 5]
Example 2
Input: the same graph, start = 3
Output: [3, 1, 5, 0, 4, 2]
Solution

The Idea

Think of the seven nodes of Example 1 as houses, and of each edge as a phone line between two of them. House 0 hears some news and calls every house it has a line to. Those houses call their own neighbours, and the news spreads. Which houses hear it, and in what order?

The graph of Example 1 drawn in bands: node 0 at the start, nodes 1 and 2 one edge away, nodes 3 and 4 two edges away, node 5 three edges away, node 6 not reached. Beside it, the queue after each step: [1, 2], [2, 3, 4], [3, 4], [4, 5], [5], empty.

Look at the left half of the picture. The nodes sit in bands by how many edges separate them from node 0. Nodes 1 and 2 are in the band labelled "1 edge away", because one edge joins each of them to 0. Nodes 3 and 4 are "2 edges away", and node 5 is "3 edges away". Node 6 has no edges at all, so it is "not reached".

Breadth-first search reads these bands from the top down. It covers the whole width of one band before it goes one band deeper, which is where the name comes from. Reading the bands that way gives 0, then 1 and 2, then 3 and 4, then 5: the answer to Example 1.

But the input never says which band a node is in. Each edge only tells us that two nodes are next to each other. How can a program still visit the nodes band by band?

It can keep a waiting line. When a node is visited, its neighbours that have not been seen yet join the back of the line, and the next node to visit always comes from the front. A line like this, where the first node in is the first node out, is called a queue.

The table on the right, "the queue, step by step", follows it. Taking 0 puts 1 and 2 in line. Taking 1 adds 3 and 4, and they wait behind 2. So every node of the "2 edges away" band joins after the whole "1 edge away" band is already waiting, and the bands come out in order.

Now look at the orange node 4. It has two edges going up, to 1 and to 2. Node 1 is taken first, and the teal edge marked "adds 4" puts 4 in the queue. One step later, in the orange row of the table, node 2 is taken. The edge from 2 to 4 is labelled "4 already seen": node 4 is in line already, so 2 adds nothing and the queue is just [3, 4].

That gives the two things a breadth-first search keeps: a queue of nodes waiting to be visited, and a mark on every node that has already joined it. Because the bands come out in order, the search reaches each node along as few edges as possible. Node 5 is reached through 1 and 3, three edges from 0, and no route from 0 to 5 is shorter.

Solution Approach

Four decisions turn the waiting line into code: how to store the graph, what the queue holds, when to mark a node as seen, and when the search stops.

Storing the graph

How does the search find a node's neighbours? Reading the edge list each time would repeat work: finding the neighbours of 4 would mean scanning all seven edges. So the first job is to build an adjacency list: for every node, a list of the nodes joined to it.

Each edge {a, b} adds b to the list of a and a to the list of b, because the edge works both ways. For Example 1 the lists are 0: [1, 2], 1: [0, 3, 4], 2: [0, 4], 3: [1, 5], 4: [1, 2, 5], 5: [3, 4], and an empty list for 6. Each list keeps the order of the edge list, and the search takes neighbours in that order.

What the queue holds

What exactly waits in line? Just node numbers. Here the queue is an ArrayDeque<Integer>: add puts a node at the back, and poll removes and returns the node at the front. Next to it, a boolean[] seen array has one slot per node and says whether that node has joined the queue yet.

When to mark a node as seen

Should a node be marked as it joins the queue, or as it leaves? Mark it as it joins. Then the check "not seen yet" stops a second neighbour from adding it again, exactly as node 2 skipped node 4 in the picture.

Marking a node only when it leaves the queue lets it wait in line more than once. A version written that way, run on Example 1, visits [0, 1, 2, 3, 4, 4, 5, 5, 5]. Node 4 is added by both 1 and 2, and node 5 is added three times, once by 3 and once by each copy of 4. The queue takes nine additions instead of six.

When the search stops

When is the search done? When the queue is empty. At that point every node that can be reached has been taken out, and no new node has joined. Node 6 never joins in Example 1, so it is not in the answer. A loop in the graph does not keep the search going either, because a node that is already seen is never added again.

To visit every node, even ones in a separate piece of the graph, an optional extension starts a new search from each node still unseen, keeping the same seen array.

Java Solution

The method bfsOrder works in these steps:

  1. First, build the adjacency list with the helper buildNeighbours(n, edges). It makes an empty list for each node, then, for each edge, adds each end to the other end's list. The result is neighbours.
  2. Create the seen array, an empty queue and an empty list order for the answer. Mark start as seen and add it to the queue.
  3. While the queue is not empty, poll the node at the front into u and append it to order.
  4. Inside, a second loop goes through neighbours.get(u). Each neighbour v that is not seen yet is marked as seen and added to the back of the queue.
  5. When the queue is empty, return order.

The main method runs both examples on the same graph, a start at node 6, which has no edges, and a square of four nodes, 0-1-2-3-0, whose edges form a loop.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class BreadthFirstSearch {

    // neighbours.get(u) lists every node joined to u, in the order the edges are given.
    static List<List<Integer>> buildNeighbours(int n, int[][] edges) {
        List<List<Integer>> neighbours = new ArrayList<>();
        for (int u = 0; u < n; u++) {
            neighbours.add(new ArrayList<>());
        }
        for (int[] edge : edges) {
            neighbours.get(edge[0]).add(edge[1]);
            neighbours.get(edge[1]).add(edge[0]); // undirected: both ends get the other
        }
        return neighbours;
    }

    static List<Integer> bfsOrder(int n, int[][] edges, int start) {
        List<List<Integer>> neighbours = buildNeighbours(n, edges);
        boolean[] seen = new boolean[n];
        Queue<Integer> queue = new ArrayDeque<>();
        List<Integer> order = new ArrayList<>();

        seen[start] = true;                   // mark when it joins the queue
        queue.add(start);
        while (!queue.isEmpty()) {
            int u = queue.poll();             // the node that has waited longest
            order.add(u);
            for (int v : neighbours.get(u)) {
                if (!seen[v]) {
                    seen[v] = true;
                    queue.add(v);
                }
            }
        }
        return order;
    }

    public static void main(String[] args) {
        int n = 7;
        int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 4}, {3, 5}, {4, 5}};
        System.out.println("start 0: " + bfsOrder(n, edges, 0));
        System.out.println("start 3: " + bfsOrder(n, edges, 3));
        System.out.println("start 6: " + bfsOrder(n, edges, 6));

        int[][] cycle = {{0, 1}, {1, 2}, {2, 3}, {3, 0}};
        System.out.println("square 0-1-2-3-0, start 0: " + bfsOrder(4, cycle, 0));
    }
}

Running it prints:

Output
start 0: [0, 1, 2, 3, 4, 5]
start 3: [3, 1, 5, 0, 4, 2]
start 6: [6]
square 0-1-2-3-0, start 0: [0, 1, 3, 2]

Look at the line for start 3, [3, 1, 5, 0, 4, 2]. Node 3's list is [1, 5], so both come straight after 3. Nodes 0 and 4 are neighbours of 1, so they follow next, and node 2 comes last, three edges from 3.

Starting at node 6 prints just [6], since its list is empty and nothing ever joins the queue. The square prints [0, 1, 3, 2] and stops, even though its edges go round in a loop. Node 1 adds 2, and when 3 is taken, 2 is already seen.

Complexity

Write V for the number of nodes (n in the code) and E for the number of edges. The search does a fixed amount of work per node and per entry in the adjacency list.

  • Time: O(V + E), because marking on the way in lets each node pass through the queue once, and its list is read once as it leaves; the lists hold 2E entries in all.
  • Space: O(V + E), because the adjacency list stores V lists with 2E entries in total, while seen, the queue and order each hold at most V nodes.

Since the search reaches every node along the fewest edges, it can also count the fewest edges from one node to another: see Shortest Path in Unweighted Graph (BFS).