0% found this document useful (0 votes)
10 views2 pages

AI Lab2 Mustafa

The document contains source code for performing breadth-first search on a graph to find the path between a source and destination node. It also includes source code for performing preorder and inorder tree traversals on a sample tree data structure. The code takes user input for the source and destination nodes, runs the BFS algorithm, and prints the path if one is found or a message if not.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

AI Lab2 Mustafa

The document contains source code for performing breadth-first search on a graph to find the path between a source and destination node. It also includes source code for performing preorder and inorder tree traversals on a sample tree data structure. The code takes user input for the source and destination nodes, runs the BFS algorithm, and prints the path if one is found or a message if not.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

AI Lab#2

Name: Mustafa Ali SIID:13035

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:

You might also like