A* search算法解迷宫
2024-09-16 09:30:10
这是一个使用A* search算法解迷宫的问题,细节请看:http://www.laurentluce.com/posts/solving-mazes-using-python-simple-recursivity-and-a-search/
Laurent Luce的A* search算法有点问题,我这边运行是死循环,稍微修改了一下。
import heapq class Cell(object):
def __init__(self, x, y, reachable):
self.reachable = reachable
self.x = x
self.y = y
self.parent = None
self.g =
self.h =
self.f = class AStar(object):
def __init__(self):
self.op = []
heapq.heapify(self.op)
self.cl = set()
self.cells = []
self.gridHeight =
self.gridWidth = def init_grid(self):
walls = ((, ), (, ), (, ), (, ), (, ),
(, ), (, ), (, ), (, ), (, ), (, ))
for x in range(self.gridWidth):
for y in range(self.gridHeight):
if (x, y) in walls:
reachable = False
else:
reachable = True
self.cells.append(Cell(x, y, reachable))
self.start = self.get_cell(, )
self.end = self.get_cell(, ) def get_heuristic(self, cell):
return * (abs(cell.x - self.end.x) + abs(cell.y - self.end.y)) def get_cell(self, x, y):
return self.cells[x * self.gridHeight + y] def get_adjacent_cells(self, cell):
cells = []
if cell.x < self.gridWidth-:
cells.append(self.get_cell(cell.x+, cell.y))
if cell.y > :
cells.append(self.get_cell(cell.x, cell.y-))
if cell.x > :
cells.append(self.get_cell(cell.x-, cell.y))
if cell.y < self.gridHeight-:
cells.append(self.get_cell(cell.x, cell.y+))
return cells def display_path(self):
cell = self.end
while cell.parent is not self.start:
cell = cell.parent
print 'path: cell: %d,%d' % (cell.x, cell.y) def update_cell(self, adj, cell):
adj.g = cell.g +
adj.h = self.get_heuristic(adj)
adj.parent = cell
adj.f = adj.h + adj.g def process(self):
heapq.heappush(self.op, (self.start.f, self.start))
while len(self.op):
f, cell = heapq.heappop(self.op)
self.cl.add(cell)
if cell is self.end:
self.display_path()
break
adj_cells = self.get_adjacent_cells(cell)
for c in adj_cells:
if c.reachable:
if c in self.cl:
if (c.f, c) in self.op:
if c.g > cell.g + :
self.update_cell(c, cell)
else:
self.update_cell(c, cell)
heapq.heappush(self.op, (c.f, c)) if __name__ == "__main__":
a = AStar()
a.init_grid()
a.process()
最新文章
- 微信小程序导航:官方工具+精品教程+DEMO集合(1月7更新)
- 制作Html标签以及表单、表格内容
- 插件~使用ECharts动态在地图上标识点~动态添加和删除标识点
- 如何rename sqlserver database
- 设计模式-观察者模式(Observer)
- VirtualBox详细教程
- syntaxhighlighter的使用
- mongodb集群【】
- MySQL - 高可用性:少宕机即高可用?
- TensorFlow windows 安装(base anaconda)
- 启动期间的内存管理之bootmem_init初始化内存管理–Linux内存管理(十二)
- 内核kmalloc内存越界排查过程(转)
- Oracle入门《Oracle介绍》第一章1-1
- 关闭swap的危害——一旦内存耗尽,由于没有SWAP的缓冲,系统会立即开始OOM
- vue-filter
- python入门第一篇
- golang 3des/ecb/cbc/pkcs5 加解密
- 关于军训的模拟赛-R2
- R 分组计算描述性统计量
- 【linux排错】";error while loading shared libraries: xxx.so.x"; 错误的原因和解决办法