Iterative Depth First Traversal of GraphA 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: 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: Solution:
Algorithm:
Iterative DFS implementation:
C++ Program: Output: Depth First Traversal is shown below: 0 3 2 1 4
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
|
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India