BFS
Breadth-first search explores a graph level by level. A queue holds the next nodes. The first time you reach a node in an unweighted graph is a shortest path.
Detailed Explanation
DFS dives. BFS spreads. You start at a source, visit all neighbours, then their neighbours, and so on. The queue is the structure: dequeue a node, enqueue its unseen neighbours. A visited set (or a boolean array on 0..n-1) prevents cycles from looping forever.
Because you visit in distance order from the source, the first time you pop the target is the fewest edges. That is why BFS is the default shortest path on unweighted graphs, grids, and implicit graphs (word ladder, lock combinations). On weighted graphs BFS is wrong; use Dijkstra.
Implementation details matter in Java. Use ArrayDeque as the queue, not LinkedList, unless you have a reason. Mark visited when you enqueue, not when you dequeue, or you enqueue the same node many times and blow memory. For grids, encode coordinates as r * cols + c or a small record. For unweighted shortest path, store dist in an array initialized to -1; dist[source] = 0.
You reach for BFS when the question is shortest number of steps, connected components in an unweighted sense (either BFS or DFS works), or level-order of a tree. You reach for DFS when you need a path, a cycle of a certain shape, or less memory on a skinny graph (recursion or an explicit stack). You reach for bidirectional BFS when both ends are known and the branching factor is high.
The cost is O(V + E) time and O(V) extra memory for the queue and visited. Wide graphs hold a whole level in the queue. On a grid that is O(min(area, perimeter of the frontier)). Recursion is not used; BFS is iterative. Do not use a PriorityQueue unless the problem is weighted.
Disconnected graphs need a loop over every node as a possible start if you must visit all components.
Code Examples
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
public class Shortest {
static int hops(List<List<Integer>> graph, int src, int dst) {
int n = graph.size();
int[] dist = new int[n];
java.util.Arrays.fill(dist, -1);
Deque<Integer> q = new ArrayDeque<>();
dist[src] = 0;
q.add(src);
while (!q.isEmpty()) {
int u = q.removeFirst();
if (u == dst) {
return dist[u];
}
for (int v : graph.get(u)) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.addLast(v); // mark on enqueue
}
}
}
return -1;
}
public static void main(String[] args) {
List<List<Integer>> g = List.of(
List.of(1, 2),
List.of(0, 2),
List.of(0, 1, 3),
List.of(2));
System.out.println(hops(g, 0, 3)); // prints: 2
}
}import java.util.ArrayDeque;
import java.util.Deque;
public class Grid {
static final int[] DR = {-1, 1, 0, 0};
static final int[] DC = {0, 0, -1, 1};
static int flood(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
Deque<int[]> q = new ArrayDeque<>();
q.add(new int[] {0, 0});
grid[0][0] = 0;
int seen = 0;
while (!q.isEmpty()) {
int[] cell = q.removeFirst();
seen++;
for (int k = 0; k < 4; k++) {
int r = cell[0] + DR[k];
int c = cell[1] + DC[k];
if (r >= 0 && c >= 0 && r < rows && c < cols && grid[r][c] == 1) {
grid[r][c] = 0;
q.addLast(new int[] {r, c});
}
}
}
return seen;
}
public static void main(String[] args) {
int[][] g = {{1, 1, 0}, {1, 0, 0}, {1, 1, 1}};
System.out.println(flood(g)); // prints: 6
}
}Common Gotchas
Mark visited on enqueue
marking on dequeue explodes the queue with duplicates.
BFS is not shortest path on weighted edges
use Dijkstra.
Implicit graphs still need a visited set
word-ladder states can loop without one.
`LinkedList` as a queue works but `ArrayDeque` is the default choice
`LinkedList` as a queue works but `ArrayDeque` is the default choice