Depth First Search is a fundamental graph traversal algorithm where we explore a path as deep as possible before backtracking and trying another path.
Unlike BFS, which moves level by level, DFS dives deep into a branch, then unwinds and explores the next one.
DFS shows up in a wide range of problems, including:
In this chapter, I’ll break down:
DFS is a powerful search algorithm for traversing a tree or graph data structure.
A simple way to think about DFS is to visualize yourself inside a maze trying to reach the exit:
DFS works on any structure that can be represented as nodes and edges like trees tries, graphs and 2D grids.
To prevent infinite loops, DFS marks nodes as visited so they aren’t processed more than once.
Lets apply DFS to this graph starting from node A.
DFS can be implemented in two ways:
Both approaches achieve the same result, but they differ in how they manage backtracking and memory usage.
Lets first look at the recursive approach:
The time complexity of DFS is O(V + E), where V is the number of vertices and E is the number of edges in the graph.
This is because each node is processed exactly once and each edge is examined at most twice in an undirected graph (once from each endpoint) and exactly once in a directed graph.
The space complexity is O(V) since we are using a visited array of size V and in the worst case, recursion stack can grow up to the number of nodes.
For Example: If the graph is structured like a linked list, the recursion depth can reach O(V).
This can lead to stack overflow in large graphs.
That’s why it’s better to use an iterative approach if memory or running into stack overflow is a concern.
Lets see how to implement DFS iteratively using a stack:
visited[]) to track visited nodes and prevent cycles.Similar to the recursive approach, the time and space complexity of this approach are both O(n).