Question: Page 2 class Graph: # graph dictionary contains all the adjacent nodes of each as key and value pair # cost _ dict contains cost

Page
2
class Graph:
# graph dictionary contains all the adjacent nodes of each as key and value pair
# cost_dict contains cost of each edge traversal of (u,v)
# final_dict contains all the possible paths from start node s to goal node g with total cost def _(self):
self.graph = dict()
self.cost_dict=dict()
self.final_dict=dict()
# u and v are nodes: edge uv with cost c
def addEdge(self,u,v,c):
if u not in self.graph:
qu=Q.PriorityQueue()
self.graph.update({u:qu})
self.graph[u].put(v)
self.cost_dict.update({(u,v):c})
# Makes a list to keep track of visited nodes
def tnode(self,n):
self.visited =[ False ]**n
def UCS_util(self,s,visited, path,goal,value):
# Appending node to the current path
path.append(s)
# Marking that node is visited
visited[s]=True
# If goal node is reached save the path and return
if goal==s:
self.final_dict.update({tuple(path):value})
return
# Checking if the adjacent node is been visited and explore the new path if haven't
for i in self.graph[s].queue:
if visited[i]==False:
# When new path is being explored add the cost of that path to cost of
entire course traversal
self.cost_dict[s,i])
# Send a copy of path list to avoid sending it by reference
self.UCS_util(i,copy.deepcopy(visited),copy.deepcopy(path),goal,value +
def UCS(self, s,goal):
self.visited[s]= True
Page
3
# List to hold all the nodes visited in path from start node to goal node path =[s]
for i in self.graph[s].queue:
if self.visited[i]== False:
# Make a variable to hold the cost of traversal value = self.cost_dict[,i
self.UCS_util(i,copy.deepcopy(self.visited),copy.deepcopy(path),goal,value)
# Display all the paths that is been discovered from start node to Goal node def all_paths(self):
# Check if there is any path
if bool(self.final_dict):
print("All the paths: ")
for 1 in self.final_dict:
print("path: ",i,"cost: ",self.final_dict[i])
else:
print("No Path exist between start and goal node")
# Find the most optimal path between start node to goal node
def optimal_path(self):
if bool(self.final_dict):
print("best path: ", min(self.final_dict, key=self.final_dict.get)
else:
print("No Path exist between start and goal node")
Page 2 class Graph: # graph dictionary contains

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!