@druceb/# Dijkstra's Algorithm

Files

- main.py

main.py

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

```
#graph = {'a':{'b':4,'c':2},'b':{'d':5,'c':1},'c':{'d':8,'e':10},'d':{'e':2,'z':6},'e':{'z':5}}
graph = {'a':{'b':10, 'c':3}, 'b':{'c':1, 'd':2}, 'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}}
#dictionary for the graph (a links to b weight 4 and c weight 2)
#This means that node ‘a’ is connected to node ‘b’ with a weight of 10 and ‘a’ is also connected to node ‘c’ with a weight of 2.
def dijkstra(graph, start, goal):
shortest_distance = {}
predecessor = {}
unseenNodes = graph
infinity = 99999
path = []
#set all final distances to infinity except the start node
for node in unseenNodes: #set all nodes apart from the starting node to infinity
shortest_distance[node] = infinity
shortest_distance[start] = 0
#loop through the unseenNodes until there are none left so we need to check if the dictionary is empty
while unseenNodes:
minNode = None
for node in unseenNodes:
if minNode is None:
minNode = node
elif shortest_distance[node]< shortest_distance[minNode]:
minNode = node
#now the minimumNode has been identified, we need to check in all it's child nodes and their weights
for childNode, weight in graph[minNode].items():
if weight + shortest_distance[minNode] < shortest_distance[childNode]:
shortest_distance[childNode] = weight + shortest_distance[minNode]
predecessor[childNode] = minNode
unseenNodes.pop(minNode)
#we have found the distance, but now we need ot find the path by running the path backward and recording every step taken from the start to the goal node
currentNode = goal
while currentNode != start:
try:
path.insert(0,currentNode)
currentNode = predecessor[currentNode]
except KeyError:
print("error")
break
path.insert(0,start)
if shortest_distance[goal] != infinity:
print("Shortest Distance: ",shortest_distance[goal])
print("Path: ", path)
strt = str(input("Start: "))
gl = str(input("Goal: "))
dijkstra(graph,strt,gl)
```

Fetching token