Introduction
Imagine you want to explore every path in a maze before moving to the next one. This is the problem DFS traversal solves: it helps you visit all parts of a structure by going deep into one path before backtracking.
Imagine exploring a cave system where you always choose one tunnel and follow it until it ends, then return to the last junction to try another tunnel. This way, you explore every tunnel deeply before moving on.
┌─────────────┐
│ Start │
└─────┬───────┘
│
▼
┌─────────────┐
│ Visit Node │
│ Deeply │
└─────┬───────┘
│
▼
┌─────────────┐
│ Explore Next│
│ Branch │
└─────┬───────┘
│
▼
┌─────────────┐
│ Backtrack │
│ if no path │
└─────┬───────┘
│
▼
┌─────────────┐
│ Repeat until│
│ all visited │
└─────────────┘def dfs(graph, start, visited=None): if visited is None: visited = set() visited.add(start) print(start) for neighbor in graph.get(start, []): if neighbor not in visited: dfs(graph, neighbor, visited) # Example graph as adjacency list graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } dfs(graph, 'A')