BFS/DFS
Graph Traversal
Learn to explore graphs systematically using Breadth-First Search and Depth-First Search with queue and stack patterns in Python.
What Is a Graph?
A graph is a data structure made of nodes (vertices) connected by edges. Graphs model real-world relationships: social networks, maps, web pages, and dependency chains.
The Adjacency List in Python
An adjacency list stores each node as a dictionary key, mapping it to a list of connected neighbors. This is the most common graph representation for BFS and DFS.
What Is Graph Traversal?
Graph traversal means visiting every reachable node starting from a given source, exactly once. The two fundamental strategies are:
BFS: Level-by-Level Exploration
DFS: Dive Deep, Then Backtrack
Queue vs. Stack: The Key Distinction
| BFS (Queue) | DFS (Stack) | |
|---|---|---|
| Data Structure | deque (FIFO) | list (LIFO) |
| Add Operation | append (right) | append (top) |
| Remove Operation | popleft() | pop() |
| Exploration Order | Level-by-level | Branch-by-branch |
| Finds Shortest Path? | Yes (unweighted) | No |
| Memory Usage | Can be high (wide graphs) | Can be high (deep graphs) |
How to Apply BFS: Step by Step
BFS Implementation in Python
DFS Implementation in Python
DFS: Recursive Version
DFS has a natural recursive form. The call stack acts as the implicit stack data structure.
Example 1: BFS Trace
Example 2: DFS Trace
Using the same graph from Example 1, let us trace iterative DFS starting at node 1:
Example 3: Finding a Path
BFS can find the shortest path (fewest edges) in an unweighted graph. Track each node's parent to reconstruct the path.
Common Mistakes to Avoid
BFS vs. DFS Summary
| BFS | DFS | |
|---|---|---|
| Data Structure | Queue (deque) | Stack (list / recursion) |
| Order | Level-by-level | Branch-by-branch |
| Shortest Path | Yes (unweighted) | No |
| Best For | Nearest neighbor, levels | Cycle detection, topological sort |
| Time | \( O(V + E) \) | \( O(V + E) \) |
| Space | \( O(V) \) | \( O(V) \) |
Question 1 of 5
Which data structure does BFS use to determine the order in which nodes are visited?
Question 2 of 5
What is the time complexity of BFS on a graph with \( V \) vertices and \( E \) edges?
Question 3 of 5
Why should you use deque.popleft() instead of list.pop(0) for BFS in Python?
Question 4 of 5
In iterative DFS, when should you check if a node has already been visited?
Question 5 of 5
Which algorithm is best suited to find the shortest path (fewest edges) from node A to node B in an unweighted graph?