๐ 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
- Start from a source vertex
- Mark it as visited
- Visit one unvisited adjacent vertex
- Repeat recursively
- 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
| Feature | DFS | BFS |
|---|---|---|
| Data Structure | Stack | Queue |
| Traversal | Depth-first | Level-first |
| Shortest Path | No | Yes |
| Memory | Less | More |
๐ 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
