AI Lab2 Mustafa
AI Lab2 Mustafa
Q1)
Source code:
graph = {
'1': ['2'],
'3': ['2', '4'],
'7': ['6'],
'2': ['3', '6', '1'],
'4': ['3', '5', '6'],
'8': ['9', '6'],
'6': ['2', '4', '7', '9', '8'],
'5': ['4'],
'9': ['6', '10', '8'],
'10': ['9']
}
def bfs(graph, start, end):
visited = []
queue = [[start]]
if start == end:
return "Source and destination are the same"
while queue:
path = queue.pop(0)
node = path[-1]
if node not in visited:
neighbors = graph[node]
for neighbor in neighbors:
new_path = list(path)
new_path.append(neighbor)
queue.append(new_path)
if neighbor == end:
return new_path
visited.append(node)
return "No path found between source and destination"
print("Following is the breadth-first search:")
inp1 = input("Enter the destination: ")
inp2 = input("Enter the source: ")
path = bfs(graph, inp2, inp1)
print("Path:", path)
Output:
AI Lab#2
Q2)
Source code:
tree = {
'1': ['2', '3'],
'2': ['4'],
'3': ['5', '6'],
'4': [],
'5': [],
'6': ['7', '8'],
'7': ['8'],
'8': []
}
visited = set()
def dfs_pre(visited, tree, node): # Preorder traversal
if node not in visited:
print(node, end=" ")
visited.add(node)
if node in tree:
for neighbour in tree[node]:
dfs_pre(visited, tree, neighbour)
def dfs_in(visited, tree, node): # Inorder traversal
if node not in visited:
visited.add(node)
if node in tree:
if len(tree[node]) > 0:
dfs_in(visited, tree, tree[node][0])
print(node, end=" ")
if len(tree[node]) > 1:
dfs_in(visited, tree, tree[node][1])
print("Preorder Traversal:")
dfs_pre(visited, tree, '1')
print("\nInorder Traversal:")
dfs_in(set(), tree, '1')
Output: