Sub topic 4
Marking Vertices as Visited When Enqueued
This chapter assumes you have already seen the basic BFS loop. It also assumes you are comfortable with Python sets and collections.deque, and that you can read Big-O notation. The question here is narrow but matters a lot: at what moment should BFS mark a vertex as visited?
Two places to mark
A BFS loop has two natural places to record that a vertex has been seen:
- On enqueue. Mark the vertex when you first discover it, at the moment you add it to the queue.
- On dequeue. Mark it later, when you remove it from the queue to process it.
Both choices can produce the correct visiting order. Only marking on enqueue guarantees that each vertex enters the queue at most once.
Seeing the difference
The code below runs both strategies on the same graph and counts how many times each one appends to the queue.
from collections import deque
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
def mark_on_enqueue(graph, start):
visited = {start}
order, enqueues = [], 1
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
enqueues += 1
return order, enqueues
def mark_on_dequeue(graph, start):
visited = set()
order, enqueues = [], 1
queue = deque([start])
while queue:
node = queue.popleft()
if node in visited:
continue # stale duplicate entry
visited.add(node)
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
enqueues += 1
return order, enqueues
print(mark_on_enqueue(graph, 'A')) # (['A', 'B', 'C', 'D', 'E', 'F'], 6)
print(mark_on_dequeue(graph, 'A')) # (['A', 'B', 'C', 'D', 'E', 'F'], 8)Both functions return the same order. The second one enqueues D twice, once from B and once from C, because D is still waiting in the queue when C looks at it. F gets enqueued twice for the same reason, once from D and once from E.
Why it matters
| Strategy | Max times a vertex is enqueued | Queue size bound | Needs a skip check on pop |
|---|---|---|---|
| Mark on enqueue | 1 | O(V) | No |
| Mark on dequeue | Up to its in-degree | O(E) | Yes |
On a dense graph, E can approach V². Marking on dequeue then lets the queue hold far more entries than there are vertices. Each stale entry also costs a pop and a membership test.
The problem gets worse once BFS records extra data. Suppose you set dist[neighbor] = dist[node] + 1 or parent[neighbor] = node every time a neighbor is not yet visited. Under mark-on-dequeue, a later, longer discovery can overwrite the first, correct value. When you mark on enqueue, the first discovery is final. Because BFS discovers vertices in layer order, that first discovery is also the shortest one.
Combining visited with other bookkeeping
You often don't need a separate set at all. A dist or parent dictionary can serve as the visited marker: a vertex is visited exactly when it has a key. Later chapters use this pattern for distances and path reconstruction.
Exercise
In an undirected graph that is a complete graph on 5 vertices, how many total enqueue operations does BFS from one vertex perform when marking on enqueue? Compare that with marking on dequeue, assuming neighbors are listed in numeric order and the start is vertex 0.
Show answer
Marking on enqueue gives 5 enqueues, one per vertex. Marking on dequeue gives 11. First, 0 is enqueued, then popping 0 enqueues 1, 2, 3, 4 (total 5). Popping 1 enqueues 2, 3, 4 again (total 8), because they are unvisited and still sitting in the queue. Popping 2 enqueues 3 and 4 (total 10). Popping 3 enqueues 4 (total 11). After that, every pop is either 4 or a stale duplicate, and no further enqueues happen.
Exercise
Why does marking on enqueue guarantee that the first distance assigned to a vertex is its shortest distance from the source?
Show answer
BFS dequeues vertices in nondecreasing order of distance. So the first time a vertex is discovered, it is discovered from a vertex in the earliest possible layer. Marking it at that moment stops any later, equal-or-longer discovery from changing its distance or parent.