-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbfs-dfs.py
42 lines (29 loc) · 928 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
# Mahdi Hassanzadeh
graph = {"5": ["3", "7"], "3": ["2", "4"], "7": ["8"], "2": [], "4": ["8"], "8": []}
# DFS Algorithm
def DFS(graph, node):
stack = [node]
visited = []
print("\nOrder of visited nodes by DFS: ", end=" ")
while stack:
s = stack.pop()
if s not in visited:
visited.append(s)
print(s, end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
stack.append(neighbour)
# BFS Algorithm
def BFS(graph, node):
queue = [node]
visited = [node]
print("\nOrder of visited nodes by BFS: ", end=" ")
while queue:
m = queue.pop(0)
print(m, end=" ")
for neighbour in graph[m]:
if neighbour not in visited:
queue.append(neighbour)
visited.append(neighbour)
BFS(graph, "5")
DFS(graph, "5")