Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 922c72b

Browse files
Depth First Search
1 parent c0a5c8d commit 922c72b

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /