Skip to content

Commit 21cc042

Browse files
author
Abhinav Gautam
committed
added documentation for dfs
1 parent f3056dd commit 21cc042

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

DFS/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Depth First Search (DFS)
2+
3+
The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.
4+
5+
Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backwards on the same path to find nodes to traverse. All the nodes will be visited on the current path till all the unvisited nodes have been traversed after which the next path will be selected.
6+
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. This will prevent you from visiting the same node more than once. If you do not mark the nodes that are visited and you visit the same node more than once, you may end up in an infinite loop.
11+
12+
## Pseudocode
13+
```
14+
DFS-iterative (G, s): //Where G is graph and s is source vertex
15+
let S be stack
16+
S.push( s ) //Inserting s in stack
17+
mark s as visited.
18+
while ( S is not empty):
19+
//Pop a vertex from stack to visit next
20+
v = S.top( )
21+
S.pop( )
22+
//Push all the neighbours of v in stack that are not visited
23+
for all neighbours w of v in Graph G:
24+
if w is not visited :
25+
S.push( w )
26+
mark w as visited
27+
28+
29+
DFS-recursive(G, s):
30+
mark s as visited
31+
for all neighbours w of s in Graph G:
32+
if w is not visited:
33+
DFS-recursive(G, w)
34+
```

0 commit comments

Comments
 (0)