Assignmnet 1
Assignmnet 1
Submitted to
Aizaz Akmal
Submitted by
M.Usama (2020-cs-611)
Department of Computer Science
University of Engineering and Technology,
Lahore, New-Campus
#DFS
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F', 'G'],
'D' : [],
'E' : [],
'F' : [],
'G' : []
}
goal = 'F'
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
if goal in visited:
break
else:
dfs(visited, graph, neighbour)
dfs(visited, graph, 'A')
#BFS
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F', 'G'],
'D' : [],
'E' : [],
'F' : [],
'G' : []
}
visited = []
queue = []
goal = 'F'
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = "\n")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
if goal in visited:
break
bfs(visited, graph, 'A')
#UCS
mygoal='F'
expque=PriorityQueue()
path=[startnode]
visited = set() # Set to keep track of visited nodes of graph.
expque.put((0,startnode,startnode))
node=expque.get()
curcost=node[0]
curname=node[1]
curpath=node[2]
if curname==goal:
print ('---Goal Found---' )
print('Path Cost: ',curcost,'Path Track: ',curpath )
return
suclist=graph[curname]
for sucnode in suclist:
if sucnode[1] not in visited:
gn=sucnode[0]+curcost
st=''
st=node[2]+' '+sucnode[1]
expque.put((gn,sucnode[1],st))
# Driver Code
print("Following is the Uniform Cost Search")
bfs(visited, graph, 'A',mygoal)