Skip to content

Commit 020b9c0

Browse files
committedJan 22, 2019
Depth First Search
1 parent a91e3b7 commit 020b9c0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 

‎Data-Structures/Graphs/dfs.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
def dfs(graph, start, visited=None):
15+
if visited is None:
16+
visited = set()
17+
visited.add(start)
18+
print(start)
19+
for i in graph[start]:
20+
if i not in visited:
21+
dfs(graph, i, visited)
22+
return visited
23+
24+
graph = {0: [2], 1: [0,2], 2: [3], 3: [1,2]}
25+
dfs(graph, 1) # 1 0 2 3

0 commit comments

Comments
 (0)