📅  最后修改于: 2022-03-11 14:45:24.334000             🧑  作者: Mango
graph = {'S':{'A':1, 'C':2}, 'A':{'B':6}, 'B':{'D':1, 'E':2}, 'C':{'A':4, 'D':3}, 'D':{'E':1}, 'E':{}} #we illustrate the dijkstra graph
def dijkstra(graph,start,target):
# we set all the default value first for all variable
shortest_distance = {}
previous = {}
unvisitNodes = graph
infinity = 999999999
pathway = []
# for loop to check wether node have visit or not
# if the node in unvisit nodes, set the shortest distance for the node to infinity
# Set the shortest distance for start node to 0
for node in unvisitNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
# while loop to decide the next node will be visit
# for first time around, it start with start node (itself)
#
while unvisitNodes:
minNode = None
for node in unvisitNodes:
if minNode is None:
minNode = node
elif shortest_distance[node] < shortest_distance[minNode]:
minNode = node
# for loop to calculate shortest distance target node form start node
# update the short distance target node from start node if calculate distance is less than known distance
# initialize the previous node for each calculate node
# decide the next node will be visit by the smallest known distance from start vertex
# add the node into visited node
for neighbourNode, weight in graph[minNode].items():
if weight + shortest_distance[minNode] < shortest_distance[neighbourNode]:
shortest_distance[neighbourNode] = weight + shortest_distance[minNode]
previous[neighbourNode] = minNode
unvisitNodes.pop(minNode)
#set currentNode into target
currentNode = target
#while loop to list all the path way for the calculate nodes
while currentNode !=start:
try:
pathway.insert(0,currentNode)
currentNode = previous[currentNode]
except KeyError:
print('Path not reach')
break
#add start node into the path way for each calculate nodes
pathway.insert(0,start)
#display the shortest distance and the path way for each target nodes
if shortest_distance[target] != infinity:
print('You are required shortest distance and path:- ')
print('From: ' + str(start))
print('To: ' + str(target))
print('Shortest distance for ' + str(target) + ' from ' + str(start) + ' is ' + str(shortest_distance[target]))
print('The path is ' + str(pathway))
# call the dijkstra function by assign the start and target nodes as the parameter
dijkstra(graph,'S','S')