From 92f300ec972bca283a28b49990176a8dcb511f01 Mon Sep 17 00:00:00 2001 From: Anoop Bhat Date: Thu, 1 Oct 2020 21:01:02 +0530 Subject: [PATCH] added dijkstras algorithm [Python] --- Python/Dijkstras.py | 50 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/Dijkstras.py diff --git a/Python/Dijkstras.py b/Python/Dijkstras.py new file mode 100644 index 0000000..6ad8d22 --- /dev/null +++ b/Python/Dijkstras.py @@ -0,0 +1,50 @@ + +import math + +def Dijkstras(graph, start, goal): + unseenNodes = graph + predecessor = {} + shortest_distance = {} + path = [] + infinty = math.inf + + for node in unseenNodes: + shortest_distance[node] = infinty + shortest_distance[start] = 0 + + while unseenNodes: + minNode = None + for node in unseenNodes: + if minNode is None: + minNode = node + + elif shortest_distance[node] < shortest_distance[minNode]: + minNode = node + + for chilNode,weight in graph[minNode].items(): + if weight + shortest_distance[minNode] < shortest_distance[chilNode]: + shortest_distance[chilNode] = weight + shortest_distance[minNode] + predecessor[chilNode] = minNode + + unseenNodes.pop(minNode) + + + currenNode = goal + while currenNode != start: + try: + path.insert(0,currenNode) + + currenNode = predecessor[currenNode] + except KeyError: + print('path not found') + break + + path.insert(0,start) + + if shortest_distance[goal] != infinty: + print('The shortest distance is ' + str(shortest_distance[goal])) + print('And the path is ' + str(path)) + + +graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2},'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}} +Dijkstras(graph, 'a', 'd') \ No newline at end of file