Sub topic 4
Marking Vertices as Visited When Enqueued
This chapter assumes you can read Python, know how set and dict membership tests work, and have seen the basic BFS loop from the previous chapter: pop a vertex from the front of a deque, then push its neighbors onto the back. Here the focus is one line of that loop, the line that marks a vertex as visited. Where you put that line decides whether BFS terminates, how much memory it uses, and whether every vertex is processed exactly once.
Why BFS Needs a Visited Marker
A graph can contain cycles, and in an undirected graph every edge is a cycle of length two (A to B and back to A). Without a record of which vertices have already been seen, BFS will push the same vertex again every time it reaches that vertex along a new edge. In a cyclic graph this never stops: the queue refills forever.
The visited marker solves this. It is a membership structure (usually a set) holding every vertex that BFS has already discovered. Before pushing a neighbor, BFS checks the marker and skips vertices it has seen.
That leaves one design question: when does a vertex count as "seen"? There are two candidate moments:
- On enqueue, when the vertex is first discovered as someone's neighbor and pushed onto the queue.
- On dequeue, when the vertex reaches the front of the queue and is processed.
Both can be made to terminate. Only the first guarantees that each vertex enters the queue at most once.
The Three States of a Vertex
During BFS every vertex is in one of three states. Textbooks often call them white, gray, and black.
| State | Meaning | In the visited set? | In the queue? |
|---|---|---|---|
| Undiscovered (white) | Not yet reached by any edge | No | No |
| Discovered (gray) | Reached, waiting to be processed | Yes | Yes |
| Finished (black) | Popped and all neighbors examined | Yes | No |
Marking on enqueue means the visited set holds every gray and every black vertex. The check neighbor not in visited then asks exactly the right question: "Is this vertex still white?"
Because the transitions only go forward, and the white-to-gray step happens only once per vertex, each vertex is pushed at most once. This is the invariant the rest of the tutorial depends on.
Mark-on-Enqueue: The Correct Pattern
from collections import deque
def bfs(graph, start):
visited = {start} # the start is discovered before the loop
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor) # mark at discovery time
queue.append(neighbor)
return order
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs(graph, 'A')) # ['A', 'B', 'C', 'D', 'E', 'F']Two details matter here.
- The start vertex goes into
visitedbefore the loop starts. If you forget this, any edge leading back to the start, including a self-loop, pushes it a second time. visited.addandqueue.appendsit together in the same branch. Treat them as a single step: whenever a vertex enters the queue, it enters the visited set at the same moment.
Mark-on-Dequeue: Correct Output, Wasted Work
A common variant marks a vertex only when it is popped. To avoid processing a vertex twice, it has to skip popped vertices that are already marked:
from collections import deque
def bfs_mark_on_dequeue(graph, start):
visited = set()
order = []
queue = deque([start])
enqueues = 1
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
def bfs_mark_on_enqueue(graph, start):
visited = {start}
order = []
queue = deque([start])
enqueues = 1
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
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D', 'E'],
'D': ['F'],
'E': ['F'],
'F': [],
}
print(bfs_mark_on_dequeue(graph, 'A')) # (['A', 'B', 'C', 'D', 'E', 'F'], 8)
print(bfs_mark_on_enqueue(graph, 'A')) # (['A', 'B', 'C', 'D', 'E', 'F'], 6)
def complete_graph(n):
return {i: [j for j in range(n) if j != i] for i in range(n)}
k100 = complete_graph(100)
print(bfs_mark_on_dequeue(k100, 0)[1]) # 4951
print(bfs_mark_on_enqueue(k100, 0)[1]) # 100Both functions return the same visiting order. In the small graph, D and F are each pushed twice by the dequeue version. B pushes D, and then C pushes D again, because D is still sitting in the queue unmarked. Each stale copy is popped later and thrown away by the continue.
On the complete graph with 100 vertices the gap grows large. The k-th processed vertex pushes every neighbor not yet popped, so the total number of pushes is 1 + 99 + 98 + ... + 0 = 4951, against 100 for mark-on-enqueue. In general, mark-on-dequeue can push one entry per edge, so the queue can hold O(E) entries instead of O(V). On a dense graph E grows like V², and that is the difference between a few kilobytes and running out of memory.
The Broken Variants
The two variants above are both correct. The bugs come from mixing them up.
| Variant | Terminates on cycles? | Each vertex processed once? | Queue size bound |
|---|---|---|---|
| Mark on enqueue, check before push | Yes | Yes | O(V) |
| Mark on dequeue, skip stale pops | Yes | Yes | O(E) |
| Mark on dequeue, no skip on pop | Yes | No, duplicates in `order` | O(E) |
| Check `visited` but never add to it | No | No | Unbounded |
| No visited structure at all | No (on any cycle) | No | Unbounded |
The third row is the usual off-by-one-line bug. Someone moves visited.add to just after popleft and drops the continue. In the example graph D and F then each show up twice in the output, and anything that runs per vertex (counting, assigning distances, appending to a path) runs twice.
Choosing the Visited Structure
The membership test runs once per edge, so it has to be O(1).
set: the default for hashable vertex labels such as strings, integers, or tuples.dict: when you also need per-vertex data. Aparentordistdictionary can serve as the visited set, sinceneighbor not in parentgives the same check. Later chapters use this.- List of booleans or
-1sentinels: when vertices are integers0..n-1or grid coordinates. Indexing a list is faster than hashing, anddist[v] == -1can mean "unvisited".
Vertices must also be hashable to go in a set. Lists are not hashable, so a grid cell must be the tuple (r, c), not [r, c].
Edge Cases Worth Testing
- Self-loops. Take
{'A': ['A']}. With the start marked before the loop,Ais processed once. If you forget to mark the start,Ais pushed a second time. - Neighbors missing from the dictionary. If
'F'appears in a neighbor list but is not a key,graph[node]raisesKeyErrorwhenFis popped. Usegraph.get(node, ())when the input may omit sink vertices. - Parallel edges.
{'A': ['B', 'B']}is safe with mark-on-enqueue. The secondBis rejected immediately. With mark-on-dequeue it adds a stale entry. - Undirected back-edges. Every edge from a child back to its parent is checked and rejected. This is expected. The check costs O(1) and is part of the O(V + E) bound covered in a later chapter.
- Disconnected graphs. One BFS marks only the start's component. Unreached vertices stay out of
visited. The connected components chapter relies on exactly that.
Exercises
Exercise
In bfsmarkon_dequeue on the example graph, which vertices are pushed onto the queue more than once, and which vertex pushes each duplicate?
Show answer
D is pushed by B and again by C, because D is still unmarked when C is processed. F is pushed by D and again by E, for the same reason. That gives 6 + 2 = 8 pushes in total.
Exercise
A teammate moves visited.add(node) to just after queue.popleft(), keeps the "if neighbor not in visited" check before pushing, and does not add a skip on pop. What does bfs return on the example graph starting from 'A'?
Show answer
['A', 'B', 'C', 'D', 'D', 'E', 'F', 'F']. D and F are each pushed twice while unmarked, and without a skip both copies are processed and appended.
Exercise
Why does mark-on-enqueue bound the queue at V entries while mark-on-dequeue only bounds it by about E + 1?
Show answer
With mark-on-enqueue, a vertex is added to visited at the same moment it is pushed, so a second push is impossible, and there are at most V pushes. With mark-on-dequeue, a vertex stays unmarked while it waits in the queue, so every processed neighbor can push it again. Each vertex pushes each of its out-neighbors at most once, so the bound is one push per edge plus the start.