RareProgramming
When can breadth-first search run indefinitely?
Short answer
A reachable cycle with no record of visited vertices
Exercise
- A reachable cycle with no record of visited vertices
- A tree processed in random order
- A stack used instead of a queue
- Isolated vertices processed later
- 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.
Platforms
- MAXIMUM
