-
Notifications
You must be signed in to change notification settings - Fork 3
/
dfs_bfs.py
43 lines (33 loc) · 797 Bytes
/
dfs_bfs.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
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
visited_bfs = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s, end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
visited_dfs = set()
def dfs(visited, graph, node):
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
print("DFS:", end=" ")
dfs(visited_dfs, graph, 'A')
print('\n')
print("BFS:", end=" ")
bfs(visited_bfs, graph, 'A')
print('\n')