💡 Summary: Exploring a Graph Layer by Layer vs. Going Deep First
Once you store a graph, the next step is visiting its nodes systematically without getting stuck in loops. Breadth-First Search (BFS) explores neighbors level by level using a queue (FIFO), which naturally finds the shortest path (fewest edges) in an unweighted graph.
Depth-First Search (DFS) follows one branch as far as possible before backtracking, using the call stack (recursion) or an explicit stack (LIFO). Both traversals track a visited set so cycles never cause infinite loops.
1. BFS vs. DFS: How Traversal Order Works
Suppose you start at node
S and visit connected nodes in a graph with V vertices and E edges:
- BFS (Queue / FIFO): Visits all immediate neighbors first (distance 1), then neighbors of those neighbors (distance 2), and so on.
- DFS (Stack / Recursion): Picks a neighbor, dives down its connected path until hitting a dead end or already-visited node, then backtracks to try remaining branches.
| Feature | BFS (Breadth-First) | DFS (Depth-First) |
|---|---|---|
| Data Structure | Queue (FIFO) | Stack / Recursion (LIFO) |
| Best For | Shortest path in unweighted graphs, nearby levels | Cycle detection, connected components, maze/path search |
| Time Complexity | O(V + E) (adjacency list) | O(V + E) (adjacency list) |
Python (bfs_and_dfs_traversal.py)
from collections import deque
graph = {
"Gate": ["Library", "Canteen"],
"Library": ["Gate", "Lab", "Auditorium"],
"Canteen": ["Gate", "Hostel"],
"Lab": ["Library", "Hostel"],
"Auditorium": ["Library"],
"Hostel": ["Canteen", "Lab"],
}
def bfs_order(adj, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in adj.get(node, []):
if nxt not in visited:
visited.add(nxt)
queue.append(nxt)
return order
def dfs_order(adj, start):
visited = set()
order = []
def dfs(node):
visited.add(node)
order.append(node)
for nxt in adj.get(node, []):
if nxt not in visited:
dfs(nxt)
dfs(start)
return order
print("BFS from Gate:", bfs_order(graph, "Gate"))
print("DFS from Gate:", dfs_order(graph, "Gate"))
Output:
BFS from Gate: ['Gate', 'Library', 'Canteen', 'Lab', 'Auditorium', 'Hostel']
DFS from Gate: ['Gate', 'Library', 'Lab', 'Hostel', 'Canteen', 'Auditorium']
2. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Five real-world situations where BFS and DFS solve everyday problems:
- 1. Fewest-Hops Route / Connection Distance (BFS): Finding the minimum number of metro stops or friend hops between two points in an unweighted graph.
- 2. Social Network "Degrees of Separation" (BFS): Checking 1st-degree friends, then 2nd-degree friends, and so on outward from a user profile.
- 3. Maze & Puzzle Path Finding (DFS / BFS): Exploring corridors in a maze; DFS dives down one hallway until blocked and backtracks, while BFS finds the shortest step count.
- 4. Detecting Cycles in Dependencies (DFS): Checking whether task or package dependencies loop back onto an ancestor currently on the recursion stack.
- 5. Web Crawler Link Exploration (BFS / DFS): Following links from a starting page to discover reachable pages without visiting the same URL twice.
Python (realtime_bfs_dfs_1_to_5.py)
from collections import deque
# 1. Shortest Number of Stops Between Two Stations using BFS
metro = {
"Central": ["Park", "Market"],
"Park": ["Central", "Univ", "Stadium"],
"Market": ["Central", "Stadium"],
"Univ": ["Park", "TechHub"],
"Stadium": ["Park", "Market", "TechHub"],
"TechHub": ["Univ", "Stadium"],
}
def shortest_hops(adj, src, dst):
if src == dst:
return [src]
visited = {src}
queue = deque([(src, [src])])
while queue:
curr, path = queue.popleft()
for nxt in adj.get(curr, []):
if nxt not in visited:
if nxt == dst:
return path + [nxt]
visited.add(nxt)
queue.append((nxt, path + [nxt]))
return []
print("1. Fewest-hop path Central -> TechHub:", shortest_hops(metro, "Central", "TechHub"))
Output:
1. Fewest-hop path Central -> TechHub: ['Central', 'Park', 'Univ', 'TechHub']
3. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-time examples showing how graph traversals appear in systems and coding problems:
- 6. Finding Connected Islands / Clusters (BFS / DFS): Grouping connected cells in a 2D grid (like connected land patches or linked components) by starting a traversal from each unvisited cell.
- 7. Flood Fill in Image & Paint Tools (BFS / DFS): Replacing connected matching pixels when you use the "paint bucket" fill tool in an editor.
- 8. Network Reachability & Broadcast Spread (BFS): Seeing which devices are reachable from a router or how quickly a message spreads outward hop by hop.
- 9. File & Folder Tree Scanning (DFS): Walking down nested subdirectories to list files or calculate total size before stepping back up to sibling folders.
- 10. Checking If a Graph Is Bipartite (BFS / DFS): Alternating two colors (Group A and Group B) across adjacent nodes to test if items can be split into two non-conflicting sets.
Python (realtime_bfs_dfs_6_to_10.py)
# 6. Counting Connected Clusters (Islands) in a 2D Grid using DFS
grid = [
[1, 1, 0, 0],
[1, 0, 0, 1],
[0, 0, 1, 1],
]
def count_clusters(mat):
rows, cols = len(mat), len(mat[0])
seen = set()
clusters = 0
def dfs(r, c):
if (r < 0 or r >= rows or c < 0 or c >= cols
or mat[r][c] == 0 or (r, c) in seen):
return
seen.add((r, c))
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
dfs(r + dr, c + dc)
for r in range(rows):
for c in range(cols):
if mat[r][c] == 1 and (r, c) not in seen:
clusters += 1
dfs(r, c)
return clusters
print("6. Connected clusters in grid:", count_clusters(grid))
Output:
6. Connected clusters in grid: 3
4. Common Pitfalls & Exam Tips for Students
Keep these points in mind when writing BFS and DFS code in labs or exams:
- Mark nodes
visitedwhen enqueuing in BFS: Adding a neighbor tovisitedas soon as you push it into the queue prevents the same node from being added multiple times at the same level. - BFS gives shortest path only for unweighted edges: If edges have different weights (like road distances or travel minutes), use a shortest-path algorithm such as Dijkstra's algorithm instead of plain BFS.
- Deep recursion on large graphs: Very deep DFS recursion in Python can hit the recursion limit, so an explicit stack or iterative approach is helpful for deep graphs.
Python (bfs_dfs_checklist.py)
reminders = [
"BFS uses a queue and finds shortest paths in unweighted graphs.",
"DFS goes deep first and is great for cycle checks and connected components.",
"Always track visited nodes so cyclic graphs do not loop forever."
]
for item in reminders:
print("*", item)
Output:
* BFS uses a queue and finds shortest paths in unweighted graphs.
* DFS goes deep first and is great for cycle checks and connected components.
* Always track visited nodes so cyclic graphs do not loop forever.