1
+ '''
2
+ The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches of all
3
+ the nodes by going ahead, if possible, else by backtracking.
4
+ Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path,
5
+ you move backwards on the same path to find nodes to traverse. All the nodes will be visited on the current path
6
+ till all the unvisited nodes have been traversed after which the next path will be selected.
7
+ This recursive nature of DFS can be implemented using stacks. The basic idea is as follows:
8
+ Pick a starting node and push all its adjacent nodes into a stack.
9
+ Pop a node from stack to select the next node to visit and push all its adjacent nodes into a stack.
10
+ Repeat this process until the stack is empty. However, ensure that the nodes that are visited are marked.
11
+ This will prevent you from visiting the same node more than once. If you do not mark the nodes that are visited
12
+ and you visit the same node more than once, you may end up in an infinite loop.
13
+
14
+ Time Complexity: O(V + E)
15
+ Space Complexity: O(V)
16
+ V is number of vertices (nodes), E is number of edges
17
+ '''
0 commit comments