Depth-First Search

Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It uses a stack (or recursion) and is useful for topological sorting, detecting cycles, and solving maze problems.

Depth-First Search Visualization

Complexity

Time Complexity: O(V + E)
Space Complexity: O(V)

Pseudocode

function DFS(graph, start, visited):
  visited.add(start)
  
  for each neighbor in graph[start]:
    if neighbor not in visited:
      DFS(graph, neighbor, visited)