python a星寻路_a*算法 python

python a星寻路_a*算法 pythonA 星算法是一种启发式搜索算法 用于寻找从起点到终点的最短路径 下面是一个简单的 Python 实现示例 使用了一个自定义的 Map2D 类来表示地图 以及一个 PriorityQueu 类来实现优先队列 pythonimport heapq class PriorityQueu def init self self elements def push self

A星算法是一种启发式搜索算法,用于寻找从起点到终点的最短路径。下面是一个简单的Python实现示例,使用了一个自定义的`Map2D`类来表示地图,以及一个`PriorityQueue`类来实现优先队列。

python

import heapq

class PriorityQueue:

def __init__(self):

self.elements = []

def push(self, item, priority):

heapq.heappush(self.elements, (priority, item))

def pop(self):

return heapq.heappop(self.elements)

class Map2D:

def __init__(self, width=20, height=20):

self.width = width

self.height = height

self.map = [[0 for _ in range(width)] for _ in range(height)]

def set_cell(self, x, y, value):

if 0 <= x < self.width and 0 <= y < self.height:

self.map[y][x] = value

def get_cell(self, x, y):

if 0 <= x < self.width and 0 <= y < self.height:

return self.map[y][x]

return None

def heuristic(a, b):

return abs(a - b) + abs(a - b) Manhattan distance

def a_star_search(graph, start, goal):

open_set = PriorityQueue()

closed_set = set()

g = {start: 0}

f = {start: heuristic(start, goal)}

parents = {start: None}

open_set.push(start, f[start])

while open_set.elements:

current = open_set.pop()

if current == goal:

path = []

while current is not None:

path.append(current)

current = parents[current]

return path[::-1]

closed_set.add(current)

for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: Right, Down, Left, Up

neighbor = (current + dx, current + dy)

tentative_g = g[current] + 1

if 0 <= neighbor < len(graph) and 0 <= neighbor < len(graph) and graph[neighbor][neighbor] == 0:

if neighbor in closed_set and tentative_g >= g.get(neighbor, 0):

continue

if neighbor not in open_set or tentative_g < g.get(neighbor, 0) or heuristic(current, neighbor) < f.get(neighbor, 0):

parents[neighbor] = current

g[neighbor] = tentative_g

f[neighbor] = tentative_g + heuristic(neighbor, goal)

open_set.push(neighbor, f[neighbor])

return None No path found

Example usage:

Initialize the map

map_instance = Map2D()

map_instance.set_cell(0, 0, 0) Walkable cell

map_instance.set_cell(1, 1, 0) Walkable cell

map_instance.set_cell(2, 2, 1) Wall

... set other cells ...

Define start and goal points

start = (0, 0)

goal = (2, 2)

Run A* search

path = a_star_search(map_instance, start, goal)

if path:

print("Path found:")

for point in path:

print(point)

else:

print("No path found.")

这个代码示例定义了一个`Map2D`类来表示地图,其中`0`表示可通行的格子,`1`表示墙壁。`a_star_search`函数实现了A星算法,使用优先队列来管理开放列表,并使用曼哈顿距离作为启发函数。

请注意,这个示例是一个简化的版本,实际应用中可能需要根据具体问题调整地图表示、启发函数和搜索逻辑。此外,示例中没有包含地图的显示功能,你可以根据需要添加绘图代码来可视化搜索过程和结果

编程小号
上一篇 2026-05-02 18:28
下一篇 2026-05-02 18:24

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/47958.html