这是一个使用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()

最新文章

  1. 微信小程序导航:官方工具+精品教程+DEMO集合(1月7更新)
  2. 制作Html标签以及表单、表格内容
  3. 插件~使用ECharts动态在地图上标识点~动态添加和删除标识点
  4. 如何rename sqlserver database
  5. 设计模式-观察者模式(Observer)
  6. VirtualBox详细教程
  7. syntaxhighlighter的使用
  8. mongodb集群【】
  9. MySQL - 高可用性:少宕机即高可用?
  10. TensorFlow windows 安装(base anaconda)
  11. 启动期间的内存管理之bootmem_init初始化内存管理–Linux内存管理(十二)
  12. 内核kmalloc内存越界排查过程(转)
  13. Oracle入门《Oracle介绍》第一章1-1
  14. 关闭swap的危害——一旦内存耗尽,由于没有SWAP的缓冲,系统会立即开始OOM
  15. vue-filter
  16. python入门第一篇
  17. golang 3des/ecb/cbc/pkcs5 加解密
  18. 关于军训的模拟赛-R2
  19. R 分组计算描述性统计量
  20. 【linux排错】&quot;error while loading shared libraries: xxx.so.x&quot; 错误的原因和解决办法

热门文章

  1. WPF Devexpress GridControl Value与Display转换
  2. GBDT+LR simple例子
  3. 安卓ios各版本及分辨率占比
  4. 写在用Mac进行Java开发之前
  5. SQL2008关于权限的解释
  6. MAC下安装MAMP后,mysql server无法启动
  7. Django项目流程
  8. Ubuntu 使用命令更新 Ubuntu 系统
  9. mongo学习链接
  10. 【51nod】1531 树上的博弈