Given a graph, the task is to print the DFS traversal of a graph which includes the every step including the backtracking.
1st step:- 0 -> 1 2nd step:- 1 -> 5 3rd step:- 5 -> 1 (backtracking step) 4th step:- 1 -> 6... and so on till all the nodes are visited. Dfs step-wise(including backtracking) is: 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10
Note: In this above diagram the weight between the edges has just been added, it does not have any role in DFS-traversal
Approach: DFS with Backtracking will be used here. First, visit every node using DFS simultaneously and keep track of the previously used edge and the parent node. If a node comes whose all the adjacent node has been visited, backtrack using the last used edge and print the nodes. Continue the steps and at every step, the parent node will become the present node. Continue the above steps to find the complete DFS traversal of the graph.
Below is the implementation of the above approach:
0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10
- Print Postorder traversal from given Inorder and Preorder traversals
- Print cousins of a given node in Binary Tree | Single Traversal
- Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
- Print level order traversal line by line | Set 1
- Find postorder traversal of BST from preorder traversal
- Backtracking | Introduction
- Sudoku | Backtracking-7
- Rat in a Maze | Backtracking-2
- Subset Sum | Backtracking-4
- Backtracking to find all subsets
- N Queen Problem | Backtracking-3
- Algorithms | Backtracking | Question 1
- Magnet Puzzle | Backtracking-9
- Rat in a Maze | Backtracking using Stack
- m Coloring Problem | Backtracking-5
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.