Breadth-First Search visualization

Explore level by level with a queue — gives shortest paths in unweighted graphs.

BFS visits every vertex at distance 1, then distance 2, and so on. A FIFO queue guarantees that order.

Marking a node visited when it is enqueued (not when dequeued) prevents the same node from entering the queue twice.

Complexity

Time: best O(V + E), average O(V + E), worst O(V + E). Space: O(V). Difficulty: Beginner.

Pseudocode

procedure BFS(G, s):
  dist[s] ← 0; queue ← [s]; visited ← {s}
  while queue not empty:
    u ← queue.dequeue()
    for each neighbor v of u:
      if v not visited:
        visited.add(v); dist[v] ← dist[u] + 1
        queue.enqueue(v)
  nodes never visited are unreachable (dist = ∞)

More graphs algorithms