def dijikstra(start,goal):
graph = {
'a': {'b': 15, 'c': 13},
'b': {'c': 12, 'd': 16},
'c': {'d': 19, 'e': 21, 'b': 12},
'd': {'e': 13, 'z': 17},
'e': {'z': 16, 'd': 13},
'z': {'d': 17}
}
shortest_distance = {}
track_predecessor = {}
unseen_nodes = graph
infinity = 999999
track_path = []
for node in unseen_nodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
while unseen_nodes:
min_distance_node = None
for node in unseen_nodes:
if min_distance_node is None:
min_distance_node = node
elif shortest_distance[node] < shortest_distance[min_distance_node]:
min_distance_node = node
path_options = graph[min_distance_node].items()
for child_node, weight in path_options:
if weight+shortest_distance[min_distance_node]<shortest_distance[child_node]:
shortest_distance[child_node] = weight+shortest_distance[min_distance_node]
track_predecessor[child_node] = min_distance_node
unseen_nodes.pop(min_distance_node)
currentNode = goal
while currentNode != start:
try:
track_path.insert(0,currentNode)
currentNode = track_predecessor[currentNode]
except KeyError:
print('path is not reachable')
break
track_path.insert(0,start)
if shortest_distance[goal] != infinity:
print('For path ' + str(track_path))
print("shortest distance is :" + str(shortest_distance[goal]))
dijikstra('a','z')
Here you can see the basic implementation of the Dijkstra's algorithm in python. By this we can get the shortest path. What I want to do here is finding the shortest path from source to end destination And also that path should go through given edges. as an example, going from a to z covering b and c so that it can achieve shortest path.
How to achieve this scenario by modifying this code