forked from ab-rohman/Open-Hack2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs_dfs.py
46 lines (38 loc) · 941 Bytes
/
bfs_dfs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
graph = {
'A' : ['B'],
'B' : ['F','G'],
'C' : ['D'],
'D' : ['H'],
'E' : [],
'F' : ['E'],
'G' : ['C'],
'H' : []
}
visitedBFS = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s, end = " ")
if s == 'D':
break
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
visitedDFS= set()
def dfs(visited, graph, node):
if node not in visited:
print(node, end = " ")
visitedDFS.add(node)
for neighbour in graph[node]:
if node == 'D':
break
dfs(visitedDFS, graph, neighbour)
print("Search result of 'D' using BFS:")
bfs(visitedBFS,graph, 'A')
print()
print("Search result of 'D' using DFS:")
dfs(visitedDFS,graph, 'A')