repl.it
@druceb/

Dijkstra 2

Python

No description

fork
loading
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
graph = {'a':{'b':10, 'c':3}, 'b':{'c':1, 'd':2}, 'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}} #directed weighted graph stored in a dictionary

def dijkstra(graph, start, goal):
  shortest_distance = {}
  predecessor = {}
  unseenNodes = graph
  infinity = 99999
  path = []

  for node in unseenNodes: #set all nodes apart from the starting node to infinity
    shortest_distance[node] = infinity
  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 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)

  currentNode = goal
  while currentNode != start:
    try:
      path.insert(0, currentNode)
      currentNode = predecessor[currentNode]
    except KeyError:
      print("Path not Reachable")
      break
  path.insert(0, start)
  if shortest_distance[goal] != infinity:
    print("Shortest distance is " + str(shortest_distance[goal]))
    print(" and the path is " + str(path))

dijkstra(graph, 'a','d')
Fetching token
?