repl.it
@MerlinKnight/

Dijkstra’s Algorithm

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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 of the graph 'a':{'b':10,'c':3} are the a Connection

def dijkstra(graph,start,goal):
  shortest_distance = {} #Constantly updated
  predecessor = {}
  unseenNodes = graph #Checks every Node
  infinity = 99999
  path = []

  #Set all nodes to infinity except for the starting node.ConnectionRefusedError
  for node in unseenNodes:
    shortest_distance[node] = infinity
    continue
  shortest_distance[start] = 0

  #Loop through the unseenNodes until there are none left so we need to check if the dictionary is empty.
  #Finds minimum Node.ConnectionRefusedError
  while unseenNodes:
    minNode = None
    for node in unseenNodes:
      if minNode == None:
        minNode = node
      elif shortest_distance[node] < shortest_distance[minNode]:
        minNode = node
      else:
        a = 1
    
    #Now the minimumNode has been identified, we need to check in all it’s child nodes and their weights.
    #Works out length
    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
      else:
        a = 2
    unseenNodes.pop(minNode)

  #Runs path backwards and records everything
  currentNode = goal
  while currentNode != start:
    try:
      path.insert(0,currentNode)
      currentNode = predecessor[currentNode]
    except KeyError:
      print("Error")
      break
  
  if shortest_distance[goal] != infinity:
    print("Shortest distance =",str(shortest_distance[goal]))
    print("Path =",str(path))

#User inputs
start = str(input("Enter start: "))
goal = str(input("Enter goal: "))
graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2},'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}}
dijkstra(graph,start,goal)
Fetching token
?