38. Depth First Search (DFS)
DFS is a graph traversal algorithm that explores as far as possible along each branch before backtracking.
Concept: Going Deep
Imagine navigating a maze. DFS is like going down one path until you hit a dead end, then returning (backtracking) and trying the next available path.
DFS typically uses a Stack (or recursion, which uses the call stack) to remember which nodes to visit next.
Algorithm Steps (Recursive)
- Start at a source node S.
- Mark S as visited.
- For every neighbor
Vof S:- If
Vis not visited, recursively call DFS onV.
- If
Use Cases
- Finding connected components.
- Detecting cycles in a graph.
- Topological sorting.