Advertisement
Guest User

dijkstra.py

a guest
May 9th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. import collections
  2.  
  3. """ TEST GRAPH
  4. graph = {
  5. 'A': {'A': -1, 'B': 2, 'C': 3, 'D': -1, 'E': -1, 'F': -1, 'G': -1, 'H': -1},
  6. 'B': {'A': 2, 'B': -1, 'C': -1, 'D': 4, 'E': -1, 'F': -1, 'G': -1, 'H': -1},
  7. 'C': {'A': 3, 'B': -1, 'C': -1, 'D': -1, 'E': 4, 'F': 5, 'G': -1, 'H': -1},
  8. 'D': {'A': -1, 'B': 4, 'C': -1, 'D': -1, 'E': -1, 'F': -1, 'G': 3, 'H': -1},
  9. 'E': {'A': -1, 'B': -1, 'C': 4, 'D': -1, 'E': -1, 'F': -1, 'G': -1, 'H': 5},
  10. 'F': {'A': -1, 'B': -1, 'C': 5, 'D': -1, 'E': -1, 'F': -1, 'G': 2, 'H': 3},
  11. 'G': {'A': -1, 'B': -1, 'C': -1, 'D': 3, 'E': -1, 'F': 2, 'G': -1, 'H': -1},
  12. 'H': {'A': -1, 'B': -1, 'C': -1, 'D': -1, 'E': 5, 'F': 3, 'G': -1, 'H': -1}
  13. }
  14. """
  15.  
  16. with open('matrixB.txt', 'r') as f:
  17. columns = next(f).split()
  18. matrix = collections.defaultdict(dict)
  19. for line in f:
  20. items = line.split()
  21. row, vals = items[0], items[1:]
  22. for col, val in zip(columns, vals):
  23. matrix[col][row] = int(val)
  24. print(matrix)
  25.  
  26. def dijkstra(graph,start,end):
  27. D = {}
  28. P = {}
  29.  
  30. for node in graph.keys():
  31. D[node] = -1
  32. P[node] = ""
  33.  
  34. D[start] = 0
  35. unseenNodes = list(graph.keys())
  36.  
  37. while len(unseenNodes) > 0:
  38. shortest = None
  39. node = ''
  40. for tempNode in unseenNodes:
  41. if shortest == None:
  42. shortest = D[tempNode]
  43. node = tempNode
  44. elif D[tempNode] < shortest:
  45. shortest = D[tempNode]
  46. node = tempNode
  47.  
  48. unseenNodes.remove(node)
  49.  
  50. for childNode, childValue in graph[node].items():
  51. if D[childNode] < D[node] + childValue:
  52. D[childNode] = D[node] + childValue
  53. P[childNode] = node
  54.  
  55. path = []
  56.  
  57. node = end
  58. while not (node == start):
  59. if path.count(node) == 0:
  60. path.insert(0,node)
  61. node = P[node]
  62. else:
  63. break
  64.  
  65. path.insert(0,start)
  66. return path
  67.  
  68. start = input("Start: ")
  69. end = input("End: ")
  70. path=dijkstra(matrix, start, end)
  71. print("The shortest path from "+start+" to "+end+" is: ",path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement