Question: Page 2 class Graph: # graph dictionary contains all the adjacent nodes of each as key and value pair # cost _ dict contains cost
Page
class Graph:
# graph dictionary contains all the adjacent nodes of each as key and value pair
# costdict contains cost of each edge traversal of
# finaldict contains all the possible paths from start node s to goal node with total cost def self:
self.graph dict
self.costdictdict
self.finaldictdict
# and are nodes: edge with cost
def addEdgeself:
if not in self.graph:
PriorityQueue
self.graph.updateu:qu
self.graphuputv
self.costdict.updateuv:c
# Makes a list to keep track of visited nodes
def tnodeself:
self.visited False
def UCSutilselfsvisited, path,goal,value:
# Appending node to the current path
path.appends
# Marking that node is visited
visitedsTrue
# If goal node is reached save the path and return
if goals:
self.finaldict.updatetuplepath:value
return
# Checking if the adjacent node is been visited and explore the new path if haven't
for in self.graphsqueue:
if visitediFalse:
# When new path is being explored add the cost of that path to cost of
entire course traversal
self.costdictsi
# Send a copy of path list to avoid sending it by reference
self.UCSutilicopy.deepcopyvisitedcopy.deepcopypathgoal,value
def UCSself sgoal:
self.visiteds True
Page
# List to hold all the nodes visited in path from start node to goal node path
for i in self.graphsqueue:
if self.visitedi False:
# Make a variable to hold the cost of traversal value self.costdict
self.UCSutilicopy.deepcopyselfvisitedcopy.deepcopypathgoal,value
# Display all the paths that is been discovered from start node to Goal node def allpathsself:
# Check if there is any path
if boolselffinaldict:
printAll the paths:
for in self.finaldict:
printpath: i"cost: self.finaldicti
else:
printNo Path exist between start and goal node"
# Find the most optimal path between start node to goal node
def optimalpathself:
if boolselffinaldict:
printbest path: minselffinaldict, keyself.finaldict.get
else:
printNo Path exist between start and goal node"
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
