Lab 4 Ai
Lab 4 Ai
Exercises
Exercise 1
Consider the following Facebook network, Draw the graph for the following network.
Each person’s account is consider as a node in a graph.
Amina is mutual friend of Sara and Razi
Razi is mutual friend of Ali and Ahmed.
Ahmed is mutual friend of Amina and Ahsan.
Rida is mutual friend of Hassan and Taha.
Uzma is mutual friend of Ahsan and Taha.
Distance of each link in 1.
Suppose Sara wants to communicate a message to Uzma. Apply appropriate search algorithm to find
path between Sara and Uzma and display the path.
visited = {}
level = {}
parent = {}
bfs_traversal_output = []
queue = Queue()
for node in graph.keys():
visited[node] = False
level[node] = -1
parent[node] = None
s = "Sara"
visited[s] = True
level[s] = 0
queue.put(s)
for v in graph[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
level[v] = level[u] + 1
queue.put(v)
v = "Uzma"
path = []
while v is not None:
path.append(v)
v = parent[v]
path.reverse()
print("Using Breath First Search")
print(path)
print("Complexity")
print(level["Uzma"])
Output:
Exercise 2
Consider the following board game and show the graph for the following board.
Each block is considered as a node of graph.
Pacman is standing at the initial position that is, Node 1 and it has to reach the final position
that is, Node 9 to end the game.
Pacman can only move 1 step forward in vertical or horizontal direction. Diagonal moves are
not allowed.
Pacman can move forward but can’t come back. Example: From node 2 move to node 3 or 5
but can’t move to node 1.
Cost or weight of moving is same for each node that is 1.
By using appropriate searching algorithm, help Pacman to reach the destination. And Display the
path from 1 to 9.
Python Code :
graph ={1: set([2,4]),2: set([1,3,5]),3: set([2,4]),4: set([3,5,9]),5: set([2,4,6,8]),6: set([1,5,7]),7:
set([6,8]),8: set([5,7,9]),9: set([4,8])}
def dfs_paths(graph, start, goal):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
stack.append((next, path + [next]))
lst = list(dfs_paths(graph,1,9))
lst.sort()
for one in lst:
print(one, end='\n')
Output:
Exercise 3
Apply above network using dictionaries and perform coding for following tasks. Perform DFS search
from node “0” to node “20” and calculate time (in sec) complexity in terms of steps. (Consider every
step take 1 sec). Use BFS algo for the same route, from node “0” to node “20”, calculate complexity
as well and provide a proper comparative analysis on, which algorithm is generating best results in
term of complexity on given route and why?
s = "0"
visited[s] = True
level[s] = 0
queue.put(s)
for v in graph[u]:
if not visited[v]:
visited[v] = True
parent[v] = u
level[v] = level[u] + 1
queue.put(v)
print("Using Breath First Search")
v = "20"
path = []
while v is not None:
path.append(v)
v = parent[v]
path.reverse()
print(path)
print("Complexity")
print(level["20"])
Output: