Skip to main content
BFS Queue

Shortest Path (Unweighted)

In an unweighted graph, BFS finds the shortest path automatically. The first time you reach a node, that's the shortest distance from the source. No need for Dijkstra's if all edges cost 1.

O(V + E)
·
O(V)

How It Works

In a graph where every edge costs the same, breadth-first search finds shortest paths by construction. The queue processes nodes in non-decreasing distance order: the source at distance 0, then all its neighbors at distance 1, and so on. The first time a node is dequeued, its recorded distance is provably minimal, because any shorter route would have enqueued it earlier. Marking nodes visited when they are enqueued — not when dequeued — prevents duplicates from bloating the queue.

BFS runs in O(V + E) time and O(V) space. Dijkstra's algorithm solves the same problem in O(E log V) with a priority queue; when all weights are equal, the plain FIFO queue replaces the heap and the log factor disappears.

Step-by-Step Visualization

Shortest path from 0 to 4 (unweighted)
0
0
1
1
2
2
3
3
4
4
Queue[(0, dist=0)]
1/3

Code

Java
static int shortestPath(List<List<Integer>> graph, int start, int end) {
  Set<Integer> visited = new HashSet<>();
  visited.add(start);
  Queue<int[]> queue = new LinkedList<>();
  queue.add(new int[]{start, 0});

  while (!queue.isEmpty()) {
    int[] curr = queue.poll();
    int node = curr[0], dist = curr[1];
    if (node == end) return dist;
    for (int nei : graph.get(node)) {
      if (!visited.contains(nei)) {
        visited.add(nei);
        queue.add(new int[]{nei, dist + 1});
      }
    }
  }
  return -1;
}

Tips & Gotchas

1BFS finds shortest path in unweighted graphs automatically
2First time a node is reached = shortest distance
3Track parent pointers to reconstruct the path

Practice Problems

  • 1Shortest Path in Binary Matrix
  • 2Word Ladder
  • 3Open the Lock
  • 4Nearest Exit from Entrance in Maze

About the BFS Queue Pattern

BFS explores nodes level by level using a queue. Enqueue the starting node, then repeatedly: dequeue a node, process it, and enqueue all its unvisited neighbors. This guarantees you visit nodes in order of their distance from the start.

Key insight

BFS = queue. If you need shortest path in an unweighted graph or level-order traversal, reach for a queue. Monotonic deques solve sliding window extremes in O(n).

Common Queue / Deque Interview Problems

  • Binary Tree Level Order Traversal
  • Sliding Window Maximum
  • Rotting Oranges
  • Shortest Path in Binary Matrix
  • Implement Queue using Stacks

Frequently Asked Questions

Why must I mark nodes visited at enqueue time rather than dequeue time?

Between being enqueued and dequeued, a node can be discovered again by other neighbors and enqueued repeatedly. The answers stay correct, but the queue can grow far beyond V entries, degrading memory and speed. Marking on enqueue guarantees each node enters the queue exactly once.

When does BFS stop being enough and Dijkstra's become necessary?

The moment edge weights differ. BFS's correctness rests on the queue holding nodes in distance order, which uniform weights guarantee for free. One special case survives: with weights of only 0 and 1, a deque-based 0-1 BFS still works in O(V + E) by pushing 0-weight edges to the front.

How do I recover the actual path, not just its length?

Store a parent pointer for each node when it is first discovered, then walk parents backward from the target and reverse. This adds O(V) space and no asymptotic time cost.