Breadth-First Search
Easy

BFS in Graphs

Finding the Shortest Path in unweighted environments.
Problem Understanding

In Graph BFS, we want to traverse a graph layer-by-layer starting from a source node. Unlike trees, graphs can have cycles (A->B->A), disconnected components, and multiple paths to the same node.

Goal:

  1. Given an unweighted graph, find the shortest path (minimum edges) from start to target.
  2. Visit all nodes reachable from start.
Algorithm Strategy

Using the Queue (FIFO) structure:

  1. Queue: Stores nodes to visit next. Initialize with [start].
  2. Visited Set: Crucial! Marks nodes as 'seen' to prevent infinite loops in cycles. Add start to visited immediately.
  3. Loop: While Queue is not empty:
    • Dequeue node U.
    • For every neighbor V of U:
      • If V is not in visited, add it to visited and Enqueue V.

This guarantees that we process nodes in order of their distance: Distance 0 (start), then Distance 1 (neighbors), then Distance 2, etc.

Interactive Visualization
Step 1 / 1

Initializing...

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep