Graph Traversal - Depth-First Search
Learn the Depth-First traversal technique to traverse graphs.
We'll cover the following
Depth-First Search approach
The Depth-First Search (DFS) algorithm is a recursive algorithm that uses the idea of Backtracking. It involves exhaustive searches of all the nodes by going ahead if possible, and if not, by backtracking. Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backward on the same path to find nodes to traverse. All the nodes will be visited on the current path till all the un-visited nodes have been traversed after which the next path will be selected.
This recursive nature of Depth-First Search can be implemented using stacks. The basic idea is as follows:
- Pick a starting node and push all its adjacent nodes into a stack.
- Pop a node from the stack to select the next node to visit and push all its adjacent nodes into a stack.
- Repeat this process until the stack is empty. However, ensure that the nodes that are visited are marked. This will prevent you from visiting the same node more than once. If you do not mark the nodes that are visited and visit the same node more than once, you may end up in an infinite loop.
Each vertex v
is initially white. It is grayed when discovered in the search and blackened when it is finished, wich happens when its adjacency list has been examined completely. This technique guarantees that each vertex v
ends up in exactly one depth-first tree so that these trees are disjoint.
Let us understand the approach by visualizing the algorithm.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.