当前位置:   article > 正文

使用A*算法求解迷宫问题_a*算法迷宫例题

a*算法迷宫例题

本题目要求读入一个5*5的迷宫,然后输出基于A*算法求解的从左上角(0,0)到右下角(4,4)的路径。

输入格式:

迷宫是一个5*5的二维数组,其中0代表可以通过,1代表墙壁不能通过。

迷宫的左上角和右下角必须是0

读入迷宫语句参考如下:

  1. str = input("")
  2. maze = eval(str)
'
运行

输出格式:

以列表形式表示的一条通路,列表中的每个元素为一个元组(x,y),x和y分别表示横纵坐标。

输入样例:

例如:

[[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,1],[1,0,1,0,1],[0,0,1,0,0]]

输出样例:

在这里给出相应的输出。例如:

[(0, 0), (0, 1), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (4, 3), (4, 4)]

 示例:

  1. import heapq
  2. def astar(maze):
  3. start = (0, 0)
  4. end = (4, 4)
  5. queue = []
  6. heapq.heappush(queue, (0, start))
  7. parent = {}
  8. g_score = {start: 0}
  9. f_score = {start: heuristic(start, end)}
  10. while queue:
  11. _, current = heapq.heappop(queue)
  12. if current == end:
  13. path = []
  14. while current in parent:
  15. path.append(current)
  16. current = parent[current]
  17. path.append(start)
  18. path.reverse()
  19. return path
  20. for neighbor in get_neighbors(current, maze):
  21. if neighbor in g_score and g_score[current] + 1 >= g_score[neighbor]:
  22. continue
  23. parent[neighbor] = current
  24. g_score[neighbor] = g_score[current] + 1
  25. f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, end)
  26. heapq.heappush(queue, (f_score[neighbor], neighbor))
  27. return None
  28. def heuristic(node, end):
  29. return abs(node[0] - end[0]) + abs(node[1] - end[1])
  30. def get_neighbors(node, maze):
  31. neighbors = []
  32. directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
  33. for direction in directions:
  34. x = node[0] + direction[0]
  35. y = node[1] + direction[1]
  36. if 0 <= x < len(maze) and 0 <= y < len(maze[0]) and maze[x][y] == 0:
  37. neighbors.append((x, y))
  38. return neighbors
  39. str = input("")
  40. maze = eval(str)
  41. path = astar(maze)
  42. print(path)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/931784
推荐阅读
相关标签
  

闽ICP备14008679号