![]() |
VOOZH | about |
The Depth First Search (DFS) algorithm is used to traverse a graph. It starts with a given source node and explores as far as possible along each branch before backtracking. It mainly traverses all vertices reachable through one adjacent, then it goes to the next adjacent.
In DFS, we explore the graph by recursively visiting nodes. The process involves two key steps: visiting nodes and exploring their neighbors. Here’s how the time complexity works:
Node Processing – Recursive Calls:
Edge Processing – Exploring Neighbors:
Putting It All Together:
Thus, the overall time complexity of DFS traversal is O(V + E), which applies in all cases (best, average, and worst).
The auxiliary space of Depth-First Search (DFS) algorithm is O(V), where V is the number of vertices in the graph, this is due to the recursion stack or visited array.
Here's why the auxiliary space complexity is O(V):
Recursion Stack:
Visited Array:
Therefore, the auxiliary space complexity of DFS is dominated by the recursion stack and the visited array, both of which require O(V) space, making the overall space complexity O(V).