01 / 20

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.

A B C D E F G Nodes (vertices) connected by edges

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

A B C D E F G Level 0 Level 1 Level 2

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

0 1 2 3 4 5 cycle edges

Cyclic Graph Trace

Step Dequeue Queue After Visited
Init-[0]{0}
10[1, 2]{0, 1, 2}
21[2, 3]{0, 1, 2, 3}
32[3, 4]{0..4}
43[4, 5]{0..5}
54[5]{0..5}
65[]{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?

Question 2 of 5

What is the time complexity of BFS on a graph with \( V \) vertices and \( E \) edges?

Question 3 of 5

When should a node be added to the visited set in BFS?

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

Question 5 of 5

What happens if you remove the visited set from BFS on a graph that contains a cycle?