Advertisement
Rakibul_Ahasan

Untitled

May 22nd, 2021
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. def aStarAlgo(start_node, stop_node):
  2. open_set = set(start_node)
  3. closed_set = set()
  4. g = {}
  5. parents = {}
  6.  
  7. g[start_node] = 0
  8.  
  9. parents[start_node] = start_node
  10.  
  11. while len(open_set) > 0:
  12. n = None
  13.  
  14. for v in open_set:
  15. if n is None or g[v] + heuristic(v) < g[n] + heuristic(n):
  16. n = v
  17.  
  18. if n == stop_node or Graph_nodes[n] is None:
  19. pass
  20. else:
  21. for (m, weight) in get_neighbors(n):
  22.  
  23. if m not in open_set and m not in closed_set:
  24. open_set.add(m)
  25. parents[m] = n
  26. g[m] = g[n] + weight
  27.  
  28.  
  29. else:
  30. if g[m] > g[n] + weight:
  31.  
  32. g[m] = g[n] + weight
  33.  
  34. parents[m] = n
  35.  
  36.  
  37. if m in closed_set:
  38. closed_set.remove(m)
  39. open_set.add(m)
  40.  
  41. if n is None:
  42. print('Path does not exist!')
  43. return None
  44.  
  45.  
  46. if n == stop_node:
  47. path = []
  48.  
  49. while parents[n] != n:
  50. path.append(n)
  51. n = parents[n]
  52.  
  53. path.append(start_node)
  54.  
  55. path.reverse()
  56.  
  57. print('Path found: {}'.format(path))
  58. return path
  59.  
  60.  
  61. open_set.remove(n)
  62. closed_set.add(n)
  63.  
  64. print('Path does not exist!')
  65. return None
  66.  
  67.  
  68.  
  69. def get_neighbors(v):
  70. if v in Graph_nodes:
  71. return Graph_nodes[v]
  72. else:
  73. return None
  74.  
  75.  
  76.  
  77. def heuristic(n):
  78. H_dist = {
  79. 'A': 11,
  80. 'B': 6,
  81. 'C': 99,
  82. 'D': 1,
  83. 'E': 7,
  84. 'G': 0,
  85.  
  86. }
  87.  
  88. return H_dist[n]
  89.  
  90.  
  91. Graph_nodes = {
  92. 'A': [('B', 2), ('E', 3)],
  93. 'B': [('C', 1), ('G', 9)],
  94. 'C': None,
  95. 'E': [('D', 6)],
  96. 'D': [('G', 1)],
  97.  
  98. }
  99.  
  100. aStarAlgo('A', 'G')
  101.  
  102.  
  103.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement