-
Notifications
You must be signed in to change notification settings - Fork 2
/
Assignment-1.py
59 lines (54 loc) · 1.39 KB
/
Assignment-1.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
47
48
49
50
51
52
53
54
55
56
57
58
59
# BFS
graph = {'A':['B', 'E', 'C'],
'B':['A', 'D', 'E'],
'D':['B', 'E'],
'E':['A', 'D', 'B'],
'C':['A', 'F', 'G'],
'F':['C'],
'G':['C']
}
visited = []
queue = []
def bfs(visited, graph, start_node, goal_node):
visited.append(start_node)
queue.append(start_node)
while queue:
m = queue.pop(0)
print(m)
if m == goal_node:
print("Node is Found !!! ")
break
else:
for n in graph[m]:
if n not in visited:
visited.append(n)
queue.append(n)
print("The BFS Traversal is : ")
bfs(visited, graph, 'A', 'D')
#DFS
graph = {'A':['B', 'E', 'C'],
'B':['A', 'D', 'E'],
'D':['B', 'E'],
'E':['A', 'D', 'B'],
'C':['A', 'F', 'G'],
'F':['C'],
'G':['C']
}
visited = []
stack = []
def dfs(graph, start, goal):
print("DFS traveral is: ")
stack.append(start)
visited.append(start)
while stack:
node = stack[-1]
stack.pop()
print("Node: ", node)
if node == goal:
print("Goal node found!")
return
for n in graph[node]:
if n not in visited:
visited.append(n)
stack.append(n)
dfs(graph, 'A', "D")