Skip to content

Commit a63a243

Browse files
Merge pull request codemistic#477 from rohansrivastava5491/patch-3
Added depth first search in python
2 parents 4d85f3e + 4983f1b commit a63a243

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Using a Python dictionary to act as an adjacency list
2+
graph = {
3+
'5' : ['3','7'],
4+
'3' : ['2', '4'],
5+
'7' : ['8'],
6+
'2' : [],
7+
'4' : ['8'],
8+
'8' : []
9+
}
10+
11+
visited = set() # Set to keep track of visited nodes of graph.
12+
13+
def dfs(visited, graph, node): #function for dfs
14+
if node not in visited:
15+
print (node)
16+
visited.add(node)
17+
for neighbour in graph[node]:
18+
dfs(visited, graph, neighbour)
19+
20+
# Driver Code
21+
print("Following is the Depth-First Search")
22+
dfs(visited, graph, '5')

0 commit comments

Comments
 (0)