Iterative Depth First Traversal of Graph

A depth-first search (DFS) is a method of traversing graphs that is similar to tree preorder traversal. The following is a recursive implementation of preorder traversal:

Depth First Traversal (or Search) for a graph is same as Depth First Traversal (DFS) for a tree. The only point is that, unlike trees, graphs can have cycles, thus a node may be visited twice. Use a boolean visited array to prevent processing a node multiple times.

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

Explanation:

DFS Diagram:

Iterative Depth First Traversal of Graph

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

Explanation:

DFS Diagram:

Iterative Depth First Traversal of Graph

Solution:

  • The depth-first search algorithm is used to traverse or search tree or graph data structures. The algorithm begins from the root node (or, in the case of a graph, any arbitrary node) and proceeds as far as feasible along each branch before backtracking. So the basic idea is to start at the root or any arbitrary node, mark the node, and then advance to the next unmarked node, and so on until there are no unmarked nearby nodes. Then go back and look for any other unmarked nodes to cross. Finally, print the paths nodes.
  • The main distinction between iterative DFS and recursive DFS is that the recursive stack has been replaced with a node stack.

Algorithm:

  • Generate a node stack and visite an array.
  • Insert the stack's root.
  • Run a loop until the stack is not empty.
  • Print the element after removing it from the stack.
  • Mark the current node and add it to the stack for every adjacent and unvisited node.

Iterative DFS implementation:

  • This is similar to BFS, with the exception that the queue has been replaced by a stack.

C++ Program:

Output:

Depth First Traversal is shown below:
0 3 2 1 4
  • Time complexity will be O(V + E), where V is the number of vertices in the graph and E is the number of edges.
  • Space Complexity will be O (V), Because an additional visited array of size V is required.

Improvement to the Previous Solution:

It should be noted that the previous implementation outputs only vertices that can be reached from a given vertex. If somehow the edges 0-3 and 0-2 are eliminated, for instance, the above code will simply print 0. Call DFS for each unvisited vertex to output all vertices of a graph.

Implementation in C++:

Output:

Depth First Traversal is shown below:
0 1 2 3 4
  • Time complexity will be O(V + E), where V is the number of vertices in the graph and E is the number of edges. (Same as recursive traversal)





Latest Courses