Breadth-First Search
BFS in Java
Learn how to traverse graphs level by level using a Queue and a visited set: the foundation of shortest-path algorithms.
Java
Graph Algorithms
What Is a Graph?
A graph is a data structure made of nodes (also called vertices) connected by edges. Graphs model relationships: social networks, maps, web pages, and more.
Why Learn BFS?
Shortest Path
In an unweighted graph, BFS always finds the shortest path from source to any reachable node.
Level-Order
BFS naturally visits nodes in layers: first distance 1, then distance 2, and so on.
Foundation
BFS underpins Dijkstra's algorithm, network broadcasting, and social-network analysis.
The Two Key Structures
Queue
A FIFO (First-In, First-Out) data structure. Nodes are enqueued when discovered and dequeued for processing. In Java: LinkedList<T> implements Queue<T>.
Visited Set
A HashSet<T> that records every node already seen. This prevents revisiting nodes and avoids infinite loops in cyclic graphs.
The BFS Algorithm
1
Enqueue the starting node and mark it visited.
2
Dequeue the front node: this is the node you are currently processing.
3
For each unvisited neighbor, mark it visited and enqueue it.
4
Repeat steps 2-3 until the queue is empty.
BFS vs DFS
| BFS | DFS | |
|---|---|---|
| Data structure | Queue (FIFO) | Stack (LIFO) |
| Traversal order | Level by level | As deep as possible first |
| Shortest path? | ✓ Unweighted graphs | ✕ Not guaranteed |
| Space complexity | \( O(V) \) | \( O(V) \) |
| Time complexity | \( O(V + E) \) | \( O(V + E) \) |
BFS in Java Code
void bfs(Map<String, List<String>> graph, String start) {
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
queue.add(start);
visited.add(start);
while (!queue.isEmpty()) {
String node = queue.poll();
System.out.print(node + " ");
for (String neighbor : graph.get(node)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
}
Step-by-Step Approach
1
Represent the graph using an adjacency list: Map<String, List<String>>.
2
Create a Queue (LinkedList) and a HashSet for visited tracking.
3
Seed the queue with the start node and add it to visited.
4
Loop while the queue is not empty: poll, process, and enqueue unvisited neighbors.
5
Terminate when the queue empties: all reachable nodes have been visited.
Worked Example: Simple Graph
Tracing the Queue
| Step | Dequeue | Queue After | Visited |
|---|---|---|---|
| Init | - | [A] | {A} |
| 1 | A | [B, C] | {A, B, C} |
| 2 | B | [C, D, E] | {A, B, C, D, E} |
| 3 | C | [D, E, F, G] | {A..G} |
| 4-7 | D, E, F, G | [] | {A..G} |
Example 2: Cyclic Graph
Cyclic Graph Trace
| Step | Dequeue | Queue After | Visited |
|---|---|---|---|
| Init | - | [0] | {0} |
| 1 | 0 | [1, 2] | {0, 1, 2} |
| 2 | 1 | [2, 3] | {0, 1, 2, 3} |
| 3 | 2 | [3, 4] | {0..4} |
| 4 | 3 | [4, 5] | {0..5} |
| 5 | 4 | [5] | {0..5} |
| 6 | 5 | [] | {0..5} |
Building the Adjacency List
Map<String, List<String>> graph = new HashMap<>();
graph.put("A", Arrays.asList("B", "C"));
graph.put("B", Arrays.asList("A", "D", "E"));
graph.put("C", Arrays.asList("A", "F", "G"));
graph.put("D", Arrays.asList("B"));
graph.put("E", Arrays.asList("B"));
graph.put("F", Arrays.asList("C"));
graph.put("G", Arrays.asList("C"));
bfs(graph, "A"); // Output: A B C D E F G
Common Mistakes
✕ Marking visited too late
Adding a node to visited only when dequeuing (not when enqueuing) lets duplicates enter the queue and wastes time.
✕ Using a Stack instead
Replacing Queue with Stack turns BFS into DFS. The traversal order changes and shortest-path guarantees are lost.
✕ Forgetting the visited set
Without a visited set, cyclic graphs cause infinite loops. Even in trees, you may revisit parent nodes.
BFS Summary
| Property | Detail |
|---|---|
| Data Structure | Queue (LinkedList) |
| Cycle Prevention | HashSet (visited) |
| Time Complexity | \( O(V + E) \) |
| Space Complexity | \( O(V) \) |
| Shortest Path | ✓ Unweighted graphs |
| Traversal Order | Level by level (layer-by-layer) |
| Java Interface | java.util.Queue<T> |
Question 1 of 5
Which data structure does BFS use to determine the order in which nodes are processed?
BFS uses a Queue (FIFO) to ensure that nodes discovered first are processed first, guaranteeing level-order traversal.
Question 2 of 5
What is the time complexity of BFS on a graph with \( V \) vertices and \( E \) edges?
BFS visits each vertex once (\( V \)) and examines each edge once (\( E \)), giving \( O(V + E) \).
Question 3 of 5
When should a node be added to the visited set in BFS?
Mark a node visited when enqueuing it. If you wait until dequeuing, duplicates can enter the queue from multiple parents.
Question 4 of 5
Given the graph below, what is the BFS traversal order starting from node 1?
Edges: 1-2, 1-3, 2-4, 3-4, 3-5
Starting at 1, its neighbors 2 and 3 are enqueued. Dequeuing 2 adds 4 to the queue. Dequeuing 3 adds 5 to the queue (its other neighbor, 4, is already in the visited set). The resulting traversal is 1, 2, 3, 4, 5.
Question 5 of 5
What happens if you remove the visited set from BFS on a graph that contains a cycle?
Without a visited set, nodes in a cycle are re-enqueued endlessly, causing an infinite loop (and eventually an OutOfMemoryError).