Skip to content
Home ยป Depth-First Search (DFS)

Depth-First Search (DFS)


๐Ÿ“˜ Depth-First Search (DFS)

1๏ธโƒฃ Introduction

Depth-First Search (DFS) is a fundamental graph traversal algorithm.

๐Ÿ”น Definition

DFS explores a graph by going as deep as possible along each branch before backtracking.

It uses a stack (LIFO) โ€” either explicitly or via recursion.


2๏ธโƒฃ Key Idea of DFS

  • Start from a source vertex
  • Explore one neighbor completely before moving to others
  • If no unvisited neighbor โ†’ backtrack

3๏ธโƒฃ Working Principle

๐Ÿ”น Steps

  1. Start from a source vertex
  2. Mark it as visited
  3. Visit one unvisited adjacent vertex
  4. Repeat recursively
  5. If no unvisited neighbor โ†’ backtrack

4๏ธโƒฃ Algorithm (DFS)

๐Ÿ”น Recursive Pseudocode

DFS(G, u):
   mark u as visited
   print u

   for each vertex v adjacent to u:
       if v is not visited:
           DFS(G, v)

๐Ÿ”น Iterative Version (Using Stack)

DFS(G, s):
   create stack S
   push s into S

   while S is not empty:
       u = pop(S)

       if u is not visited:
           mark u as visited
           print u

           for each neighbor v of u:
               push v into stack

5๏ธโƒฃ Example

๐Ÿ”น Graph:

      A
     / \
    B   C
   / \   \
  D   E   F

๐Ÿ”น DFS Traversal (Starting from A)

A โ†’ B โ†’ D โ†’ E โ†’ C โ†’ F

โœ” Goes deep first, then backtracks


6๏ธโƒฃ Recursion Trace (Concept)

  • Visit A
  • Go to B
  • Go to D โ†’ no more neighbors โ†’ backtrack
  • Go to E โ†’ backtrack
  • Go to C
  • Go to F

7๏ธโƒฃ Time Complexity

๐Ÿ”น Using Adjacency List

[
O(V + E)
]

๐Ÿ”น Using Adjacency Matrix

[
O(V^2)
]


8๏ธโƒฃ Space Complexity

  • Recursive stack / explicit stack โ†’ O(V)
  • Visited array โ†’ O(V)

9๏ธโƒฃ Characteristics of DFS

โœ” Depth-wise traversal
โœ” Uses recursion or stack
โœ” Backtracking-based
โœ” Does not guarantee shortest path


๐Ÿ”Ÿ Applications of DFS

  • Cycle detection in graphs
  • Topological sorting
  • Connected components
  • Maze solving
  • Path finding
  • Strongly connected components

1๏ธโƒฃ1๏ธโƒฃ Advantages

โœ” Simple to implement
โœ” Uses less memory than BFS
โœ” Useful for deep traversal problems


1๏ธโƒฃ2๏ธโƒฃ Disadvantages

โœ– Does not guarantee shortest path
โœ– May go deep into unnecessary paths
โœ– Recursive stack overflow (for large graphs)


1๏ธโƒฃ3๏ธโƒฃ DFS vs BFS

FeatureDFSBFS
Data StructureStackQueue
TraversalDepth-firstLevel-first
Shortest PathNoYes
MemoryLessMore

๐Ÿ”š Conclusion

Depth-First Search is a powerful graph traversal algorithm that explores nodes deeply before backtracking.

DFS is ideal for problems requiring full exploration like cycle detection and topological sorting.


๐Ÿ“Œ Exam Tip

๐Ÿ‘‰ Always include:

  • Recursive algorithm
  • Stack concept
  • Example traversal
  • Complexity