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{a, b}start
Breadth-first search visits startstart
Example 1
Output: [0, 1, 2, 3, 4, 5]
Example 2
Output: [3, 1, 5, 0, 4, 2]
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?
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}
What the queue holds
What exactly waits in line? Just node numbers. Here the queue is an ArrayDeque<Integer>addpollboolean[] seen
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]
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
Java Solution
The method bfsOrder
- First, build the adjacency list with the helper
. It makes an empty list for each node, then, for each edge, adds each end to the other end's list. The result isbuildNeighbours(n, edges) .neighbours - Create the
array, an emptyseen and an empty listqueue for the answer. Markorder as seen and add it to the queue.start - While the queue is not empty,
the node at the front intopoll and append it tou .order - Inside, a second loop goes through
. Each neighbourneighbours.get(u) that is not seen yet is marked as seen and added to the back of the queue.v - When the queue is empty, return
.order
The main
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:
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]
Starting at node 6 prints just [6][0, 1, 3, 2]
Complexity
Write V for the number of nodes (n
- 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
, the queue andseen each hold at most V nodes.order
Since the search reaches every node along the fewest edges, it can also count the fewest edges from one node to another: see