python寻路_Python的 - 加快一个A星寻路算法

I've coded my first slightly-complex algorithm, an implementation of the A Star Pathfinding algorithm. I followed some Python.org advice on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each node is really just a tile in a grid of nodes, hence how I'm working out the heuristic and my occasional reference to them.

Thanks to timeit I know that I can run this function successfully a little over one hundred times a second. Understandably this makes me a little uneasy, this is without any other 'game stuff' going on, like graphics or calculating game logic. So I'd love to see whether any of you can speed up my algorithm, I am completely unfamiliar with Cython or it's kin, I can't code a line of C.

Without any more rambling, here is my A Star function.

def aStar(self, graph, current, end):

openList = []

closedList = []

path = []

def retracePath(c):

path.insert(0,c)

if c.parent == None:

return

retracePath(c.parent)

openList.append(current)

while len(openList) is not 0:

current = min(openList, key=lambda inst:inst.H)

if current == end:

return retracePath(current)

openList.remove(current)

closedList.append(current)

for tile in graph[current]:

if tile not in closedList:

tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10

if tile not in openList:

openList.append(tile)

tile.parent = current

return path

解决方案

An easy optimization is to use sets instead of lists for the open and closed sets.

openSet = set()

closedSet = set()

This will make all of the in and not in tests O(1) instead of O(n).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值