01 / 21

Tracking Visited Nodes

Learn how to prevent infinite cycles in graph traversal by keeping track of which nodes you have already explored using Python sets.

Computer Science Graph Algorithms

What Is a Graph?

A graph is a data structure made of nodes (also called vertices) connected by edges. Graphs model relationships: social networks, maps, web pages, dependencies, and more.

A B C D E 5 nodes, 6 edges

The Cycle Problem

When you traverse a graph, edges can lead you back to a node you already visited. Without protection, your program enters an infinite loop, revisiting the same nodes forever.

A B C cycle! Traversal trace: A → B → C → A → B → C → A → ... forever!

What Does "Visited" Mean?

A node is visited once your algorithm has processed it (or added it to a processing queue). The key idea: never process a node more than once.

Unvisited
Node has not been seen yet. It can be explored freely.
In Progress
Node is in the queue or stack, waiting to be fully processed.
Visited
Node has been fully processed. Skip it if encountered again.

The Core Rule

Pick next node In visited? Skip it Add to visited Process node No Yes

This simple check is all you need to prevent cycles. Every graph traversal algorithm (BFS, DFS, Dijkstra) uses this pattern.

Why a Set?

Python offers several data structures, but sets are ideal for visited tracking. Here is why:

Data Structure Lookup Time Duplicates? Best For
list \( O(n) \) Allows Ordered data
set \( O(1) \) Rejects Visited tracking
dict \( O(1) \) Keys unique Key-value pairs

Set vs List for Visited

visited = set()
✓ \( O(1) \) lookup with in
✓ \( O(1) \) insertion with .add()
✓ Automatically prevents duplicates
✓ Scales well to large graphs
visited = []
✕ \( O(n) \) lookup with in
✕ Must manually check before appending
✕ Allows accidental duplicates
✕ Slows down with large graphs

How to Apply the Pattern

1
Initialize an empty set: visited = set()
2
Before processing a node, check: if node in visited: skip
3
If not visited, add it: visited.add(node)
4
Process the node (print, compute, enqueue neighbors, etc.)
5
Repeat for each neighbor. The visited set guarantees no node is processed twice.

Example: BFS with Visited Set

from collections import deque def bfs(graph, start): visited = set() queue = deque([start]) visited.add(start) while queue: node = queue.popleft() print(node) # process for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor)

Example: DFS with Visited Set

def dfs(graph, node, visited=None): if visited is None: visited = set() if node in visited: return visited.add(node) print(node) # process for neighbor in graph[node]: if neighbor not in visited: dfs(graph, neighbor, visited)

Walkthrough: BFS on a Cyclic Graph

1 2 3 4 cycle edge Step-by-step: Step 1: Process 1. Enqueue 2, 3. visited = {1, 2, 3} Step 2: Process 2. Enqueue 4. visited = {1, 2, 3, 4} Step 3: Process 3. Neighbor 4 is visited. visited = {1, 2, 3, 4} Step 4: Process 4. Neighbor 1 is visited. visited = {1, 2, 3, 4} ✓ Cycle safely avoided! Output: 1, 2, 3, 4

Larger Graph Example

graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] } bfs(graph, 'A') # Output: A, B, C, D, E, F

Representing a Graph in Python

The most common representation is an adjacency dictionary: each key is a node, and its value is a list of neighbors.

# Adjacency dictionary graph = { 0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2] } # Get neighbors of node 0 print(graph[0]) # [1, 2]

When to Mark as Visited

A subtle but important decision: when do you add a node to the visited set?

BFS: On Enqueue
Mark visited when you add a node to the queue. This prevents the same node from being added multiple times by different neighbors.
DFS: On Entry
Mark visited at the start of the recursive call (or when you push onto the stack). This prevents re-entering a node from a cycle.

Common Mistakes

✕ Forgetting the visited set
Without it, cyclic graphs cause infinite loops and stack overflows in recursive DFS.
✕ Using a list instead of a set
Checking node in list is \( O(V) \), making the traversal \( O(V^2) \) or worse.
✕ Marking visited too late
In BFS, marking on dequeue lets duplicate entries flood the queue. Mark on enqueue.

Summary Table

Aspect BFS DFS (Recursive) DFS (Iterative)
Data structure Queue (deque) Call stack Explicit stack
Visited type set set (param) set
Mark visited On enqueue On entry On push
Cycle protection ✓ ✓ ✓
Time complexity \( O(V + E) \) \( O(V + E) \) \( O(V + E) \)

Question 1 of 5

What is the primary reason for tracking visited nodes during graph traversal?

Question 2 of 5

Which Python data structure is best for storing visited nodes and why?

Question 3 of 5

In a BFS implementation, when should you add a node to the visited set?

Question 4 of 5

What is the bug in this DFS implementation?

Question 5 of 5

After BFS completes, what does the visited set contain?