Breadth-first search
32 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Breadth-first search explores a graph level by level using a queue, finding the shortest unweighted paths.
A queue and a visited array
Breadth-first search (BFS) explores a graph level by level from a start node using a queue, so it finds the shortest path in an unweighted graph.
Breadth-first search radiates outward from a source vertex like ripples across water. It explores all immediate neighbours at distance 1 before visiting any vertices at distance 2. This level-order progression requires a First-In-First-Out Queue in Java.
BFS explores the graph level by level
Step 1 of 5
Example 1 · Standard BFS Traversal in Java
import java.util.*;
public class Main { static void bfs(List<List<Integer>> adj, int start, int n) { boolean[] visited = new boolean[n]; Queue<Integer> queue = new LinkedList<>();
visited[start] = true; queue.offer(start);
System.out.print("BFS traversal: "); while (!queue.isEmpty()) { int u = queue.poll(); System.out.print(u + " ");
for (int v : adj.get(u)) { if (!visited[v]) { visited[v] = true; queue.offer(v); } } } System.out.println(); }
public static void main(String[] args) { int n = 5; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).addAll(Arrays.asList(1, 2)); adj.get(1).addAll(Arrays.asList(0, 3)); adj.get(2).addAll(Arrays.asList(0, 4)); adj.get(3).add(1); adj.get(4).add(2);
bfs(adj, 0, n); }}BFS traversal: 0 1 2 3 4
What this code does
- Queue starts with root node 0.
- Level 1 neighbours 1 and 2 are processed before level 2 nodes 3 and 4.
- Output matches level-by-level traversal order.
A boolean visited array prevents getting trapped in infinite loops when graphs have cycles. Always mark a vertex visited immediately when offering it into the queue. Delaying the visited check until poll causes redundant duplicate queue insertions and high memory usage. Poll the front vertex, process it, and offer all unvisited neighbours to the back of the queue.
Order of execution
Put BFS in order
Run breadth-first search from a start vertex. Put the steps in the order the code runs them.
Levels, distances, and shortest paths in unweighted graphs
Because BFS visits nodes in strictly increasing distance from the source, it computes shortest unweighted paths. With unit edge weights, the first time BFS reaches vertex v gives its shortest path.
Example 2 · Brute force: try every path, exponential time, O(V) space
import java.util.*;
public class Main { static List<List<Integer>> adj = new ArrayList<>(); static int best = Integer.MAX_VALUE;
static void explore(int u, int target, boolean[] onPath, int steps) { if (u == target) { best = Math.min(best, steps); return; } onPath[u] = true; for (int v : adj.get(u)) { if (!onPath[v]) explore(v, target, onPath, steps + 1); // tries every simple path } onPath[u] = false; // free u for other paths }
public static void main(String[] args) { int n = 6; for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {2, 4}, {4, 5}}; for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); } explore(0, 5, new boolean[n], 0); System.out.println("shortest steps 0 -> 5: " + best); }}shortest steps 0 -> 5: 3
What this code does
- The search follows every possible path from 0 to 5 and keeps the smallest step count.
- Marking a vertex off the path and freeing it again lets the search try every route, so the number of paths can grow exponentially.
- BFS finds the same answer without ever trying a second route to a vertex.
Example 3 · Optimal: BFS, O(V + E) time, O(V) space
import java.util.*;
public class Main { static int[] shortestDistances(List<List<Integer>> adj, int start, int n) { int[] dist = new int[n]; Arrays.fill(dist, -1); Queue<Integer> q = new LinkedList<>();
dist[start] = 0; q.offer(start);
while (!q.isEmpty()) { int u = q.poll(); for (int v : adj.get(u)) { if (dist[v] == -1) { dist[v] = dist[u] + 1; q.offer(v); } } } return dist; }
public static void main(String[] args) { int n = 4; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).addAll(Arrays.asList(1, 2)); adj.get(1).addAll(Arrays.asList(0, 3)); adj.get(2).add(0); adj.get(3).add(1);
int[] d = shortestDistances(adj, 0, n); for (int i = 0; i < n; i++) { System.out.println("Distance to " + i + ": " + d[i]); } }}Distance to 0: 0 Distance to 1: 1 Distance to 2: 1 Distance to 3: 2
What this code does
- dist array initialized to -1 serves as visited tracker and distance store.
- Distance increments by 1 for each outward level.
- Node 3 requires 2 edge hops from source 0.
- It is faster because BFS reaches each vertex first by its shortest route and never explores that vertex again.
Example 4 · Path Reconstruction Using Parent Array
import java.util.*;
public class Main { static List<Integer> findPath(List<List<Integer>> adj, int start, int target, int n) { int[] parent = new int[n]; Arrays.fill(parent, -1); boolean[] visited = new boolean[n]; Queue<Integer> q = new LinkedList<>();
visited[start] = true; q.offer(start);
while (!q.isEmpty()) { int u = q.poll(); if (u == target) break; for (int v : adj.get(u)) { if (!visited[v]) { visited[v] = true; parent[v] = u; q.offer(v); } } }
List<Integer> path = new ArrayList<>(); for (int at = target; at != -1; at = parent[at]) { path.add(at); if (at == start) break; } Collections.reverse(path); return path; }
public static void main(String[] args) { int n = 4; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).add(1); adj.get(1).addAll(Arrays.asList(0, 2)); adj.get(2).addAll(Arrays.asList(1, 3)); adj.get(3).add(2);
System.out.println("Shortest path 0 to 3: " + findPath(adj, 0, 3, n)); }}Shortest path 0 to 3: [0, 1, 2, 3]
What this code does
- parent array tracks which node discovered each vertex.
- Backtracking from target to start builds the reverse path.
- Reversing the collected list gives the forward path.
Maintain an integer array dist initialized to -1, with dist[start] set to 0. When vertex u discovers unvisited neighbour v, set dist[v] = dist[u] + 1. To reconstruct the complete path, maintain a parent array where parent[v] = u. Backtracking from destination to start using parent pointers yields the exact sequence of vertices.
Complexity analysis and disconnected graphs
BFS runs in O(V + E) time: each vertex enters and leaves the queue once, and each edge is examined once (twice in an undirected graph). The queue and visited array use O(V) space.
boolean[] visited = new boolean[n];for (int s = 0; s < n; s++) { // outer loop: covers disconnected parts if (visited[s]) continue; Queue<Integer> q = new ArrayDeque<>(); visited[s] = true; q.offer(s); while (!q.isEmpty()) { int u = q.poll(); // each vertex polled once: O(V) for (int v : adj.get(u)) { // each edge checked once or twice: O(E) if (!visited[v]) { visited[v] = true; q.offer(v); } } }}For a disconnected graph, add an outer loop over vertices 0 to V - 1 and start a new BFS from every vertex that is still unvisited, so no component is missed.
Find the bug
Find the BFS bug
Each snippet is part of a BFS. Tap the wrong line.
Vertices are being added to the queue more than once.
Round 1 of 3Next step
Check your understanding
10 quick questions