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.
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.
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.
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.
The Core Rule
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
✓ \( O(1) \) insertion with .add()
✓ Automatically prevents duplicates
✓ Scales well to large graphs
✕ Must manually check before appending
✕ Allows accidental duplicates
✕ Slows down with large graphs
How to Apply the Pattern
Example: BFS with Visited Set
Example: DFS with Visited Set
Walkthrough: BFS on a Cyclic Graph
Larger Graph Example
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.
When to Mark as Visited
A subtle but important decision: when do you add a node to the visited set?
Common Mistakes
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
Consider this code:
def dfs(graph, node, visited):
visited.add(node)
print(node)
for neighbor in graph[node]:
dfs(graph, neighbor, visited)
What is the bug in this DFS implementation?
Question 5 of 5
Given this graph and BFS starting from node A:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
After BFS completes, what does the visited set contain?