ASSIGNMENT NO.
-- 7
from collections import deque
locations = ['A', 'B', 'C', 'D']
locations_index = {name: idx for idx, name in enumerate(locations)}
# ----- DFS using Adjacency Matrix -----
adj_matrix = [
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]
def dfs_matrix(start):
visited = [False] * len(locations)
result = []
def dfs(node):
visited[node] = True
[Link](locations[node])
for neighbour in range(len(adj_matrix)):
if adj_matrix[node][neighbour] == 1 and not visited[neighbour]:
dfs(neighbour)
dfs(locations_index[start])
return result
# ----- BFS using Adjacency List -----
adj_list = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
ASSIGNMENT NO. -- 7
'D': ['B', 'C']
def bfs_list(start):
visited = set([start])
queue = deque([start])
result = []
while queue:
node = [Link]()
[Link](node)
for neighbour in adj_list[node]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)
return result
# ----- Menu -----
def menu():
while True:
print("\nMenu")
print("1. DFS")
print("2. BFS")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
start_location = 'A'
dfs_result = dfs_matrix(start_location)
print("DFS Traversal (using adjacency matrix):", dfs_result)
elif choice == '2':
ASSIGNMENT NO. -- 7
start_location = 'A'
bfs_result = bfs_list(start_location)
print("BFS Traversal (using adjacency list):", bfs_result)
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice, try again!")
# Run program
menu()