Depth First Search (DFS) Algorithm

Master graph traversal with DFS - from basics to advanced applications

What is Depth First Search?

Definition: Depth First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It uses a stack data structure (either explicitly or via recursion) to remember vertices to visit next.

DFS starts at a root node and explores each branch completely before moving to the next branch. This "depth-first" approach contrasts with Breadth First Search (BFS), which explores all neighbors at the current depth before moving deeper.

Key Concept: DFS goes deep into the graph before going wide. Think of it as exploring a maze by always taking the first unexplored path until you hit a dead end, then backtracking.

How DFS Works

Algorithm Steps

  1. Start: Mark the starting vertex as visited
  2. Explore: Visit an adjacent unvisited vertex
  3. Recurse: Recursively apply DFS to that vertex
  4. Backtrack: When no unvisited adjacent vertices remain, backtrack to the previous vertex
  5. Repeat: Continue until all reachable vertices are visited

Traversal Order Example

For a graph with vertices A-B-C-D-E connected as: A→B→D, A→C→E

DFS Order: A → B → D (backtrack) → C → E

BFS Order (for comparison): A → B → C → D → E

Implementation

Recursive Implementation (Python)

def dfs_recursive(graph, vertex, visited=None): if visited is None: visited = set() # Mark current vertex as visited visited.add(vertex) print(vertex, end=' ') # Recursively visit all unvisited neighbors for neighbor in graph[vertex]: if neighbor not in visited: dfs_recursive(graph, neighbor, visited) return visited # Example usage graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } dfs_recursive(graph, 'A') # Output: A B D E F C

Iterative Implementation (Using Stack)

def dfs_iterative(graph, start): visited = set() stack = [start] while stack: vertex = stack.pop() if vertex not in visited: visited.add(vertex) print(vertex, end=' ') # Add unvisited neighbors to stack for neighbor in reversed(graph[vertex]): if neighbor not in visited: stack.append(neighbor) return visited

Time & Space Complexity

Complexity Type Value Explanation
Time Complexity O(V + E) V = vertices, E = edges. Each vertex and edge is visited once.
Space Complexity (Recursive) O(V) Call stack can go as deep as the number of vertices
Space Complexity (Iterative) O(V) Explicit stack stores vertices
Performance Note: DFS is more memory-efficient than BFS for deep graphs but can be slower for finding shortest paths.

Real-World Applications

Pathfinding

Finding paths in mazes, games, and navigation systems. DFS can find any path (not necessarily shortest).

Cycle Detection

Detecting cycles in graphs, useful for deadlock detection in operating systems and dependency analysis.

Topological Sorting

Ordering tasks with dependencies, used in build systems and course scheduling.

Connected Components

Finding all connected parts of a graph, used in network analysis and image segmentation.

Solving Puzzles

Sudoku, N-Queens, and other backtracking problems use DFS to explore solution spaces.

Web Crawling

Search engines use DFS-like algorithms to crawl websites by following links deeply.

Worked Examples

Example 1: Tree Traversal

Problem: Traverse a binary tree using DFS (in-order, pre-order, post-order).

Pre-order DFS (Root → Left → Right):

def preorder_dfs(node): if node is None: return print(node.value) # Visit root preorder_dfs(node.left) # Traverse left preorder_dfs(node.right) # Traverse right

Use Case: Creating a copy of the tree, prefix expression evaluation

Example 2: Detecting Cycles

Problem: Detect if a directed graph contains a cycle.

def has_cycle(graph): visited = set() rec_stack = set() # Recursion stack def dfs(vertex): visited.add(vertex) rec_stack.add(vertex) for neighbor in graph[vertex]: if neighbor not in visited: if dfs(neighbor): return True elif neighbor in rec_stack: return True # Back edge found = cycle rec_stack.remove(vertex) return False for vertex in graph: if vertex not in visited: if dfs(vertex): return True return False

DFS vs BFS Comparison

Feature DFS BFS
Data Structure Stack (or recursion) Queue
Exploration Goes deep first Goes wide first
Memory Usage Lower for deep graphs Higher for wide graphs
Shortest Path Not guaranteed Guaranteed (unweighted)
Best For Pathfinding, cycles, topological sort Shortest path, level-order traversal

Key Takeaways

Remember:
  • DFS explores depth before breadth using a stack
  • Time complexity: O(V + E), Space: O(V)
  • Can be implemented recursively or iteratively
  • Excellent for cycle detection and topological sorting
  • Not optimal for finding shortest paths
  • Essential for backtracking algorithms