← All questions
RareProgramming

When can breadth-first search run indefinitely?

Short answer
A reachable cycle with no record of visited vertices

Exercise

  1. A reachable cycle with no record of visited vertices
  2. A tree processed in random order
  3. A stack used instead of a queue
  4. Isolated vertices processed later
  5. Disconnected components

Solution

A cycle can keep adding previously reached vertices to the queue.

Take two vertices A and B with an edge in each direction. Removing A adds B, and removing B adds A again. If the pair is reachable from the start and the search has not stopped at a target, the queue never empties. Marking vertices stops the repeated expansion.

A → B, B → A: [A] → [B] → [A] → [B] → … visited = {A, B}: A → B → ∅.

The queue keeps vertices in discovery order. The visited set serves a different purpose: it records that a neighbour has appeared before. The order of removal alone cannot stop a vertex being added again.

Graph traversal

Platforms

  • MAXIMUM

Download now and try it for free on your own tasks!

10 15 free credits • No credit card required
Version: Loading…

Choose the Windows app or the Chrome extension with phone controls.