Iterative Depth First Traversal of Graph
- Difficulty Level : Easy
- Last Updated : 26 Nov, 2021
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array.
Input: n = 4, e = 6
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3
Output: DFS from vertex 1 : 1 2 0 3
Input: n = 4, e = 6
2 -> 0, 0 -> 2, 1 -> 2, 0 -> 1, 3 -> 3, 1 -> 3
Output: DFS from vertex 2 : 2 0 1 3
The recursive implementation of DFS is already discussed: previous post.
- Approach: Depth-first search is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. So the basic idea is to start from the root or any arbitrary node and mark the node and move to the adjacent unmarked node and continue this loop until there is no unmarked adjacent node. Then backtrack and check for other unmarked nodes and traverse them. Finally print the nodes in the path.
The only difference between iterative DFS and recursive DFS is that the recursive stack is replaced by a stack of nodes.
- Created a stack of nodes and visited array.
- Insert the root in the stack.
- Run a loop till the stack is not empty.
- Pop the element from the stack and print the element.
- For every adjacent and unvisited node of current node, mark the node and insert it in the stack.
- Implementation of Iterative DFS: This is similar to BFS, the only difference is queue is replaced by stack.
Following is Depth First Traversal 0 3 2 1 4
- Complexity Analysis:
- Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
- Space Complexity: O(V). Since an extra visited array is needed of size V.
Modification of the above Solution: Note that the above implementation prints only vertices that are reachable from a given vertex. For example, if the edges 0-3 and 0-2 are removed, then the above program would only print 0. To print all vertices of a graph, call DFS for every unvisited vertex.
Following is Depth First Traversal 0 1 2 3 4
Like recursive traversal, the time complexity of iterative implementation is O(V + E).
This article is contributed by Shivam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.