我已经实现了一个 A* 算法来找到网格世界中两点之间的最短路径。对于较大的路径长度,该算法需要很长时间。我首先想知道我的实现是否正确,是否可以进行任何优化?
该aStar
算法的参数是您的当前位置和您希望作为元组前往的位置(x,y)
。
节点的Node.value
是行进方向 (NSEW),getAdjacentNodes()
返回与我们可以行进到的节点直接相邻的节点列表。
#Perform an A* search to find the best path to the dirt
def aStar(self, current, end):
openSet = set() #Set of explorable nodes
openHeap = [] #All paths heap, lowest cost on top
closedSet = set() #Best path so far
curNode = Node(0, current, self.manHatDist(current, end))
openSet.add(curNode)
openHeap.append((curNode.cost,curNode))
while openSet:
curNode = heapq.heappop(openHeap)[1]
if curNode.pos == end:
return self.getDirections(curNode)
openSet.remove(curNode)
closedSet.add(curNode)
for tile in self.getAdjacentNodes(curNode.pos):
if tile not in closedSet:
tile.parent = curNode
tile.cost = self.manHatDist(curNode.pos, end) + self.euclidDist(curNode.pos, current) + curNode.cost
if tile not in openSet:
openSet.add(tile)
heapq.heappush(openHeap, (tile.cost,tile))
return []
#Get the moves made to get to this endNode
def getDirections(self, endNode):
moves = []
tmpNode = endNode
while tmpNode.parent is not None:
moves.append(tmpNode.value)
tmpNode = tmpNode.parent
moves.reverse()
return moves
节点类
# Node class for A* search
class Node:
def __init__(self, value, pos, cost):
self.pos = pos
self.cost = cost
self.value = value
self.parent = None
def __lt__(a, b):
if(a.cost < b.cost):
return 1
return 0
def __gt__(a, b):
if(a.cost > b.cost):
return 1
return 0
编辑 - 这是getAdjacentNodes
方法
#Return all possible moves from given tile as Node objects
def getAdjacentNodes(self, curPos):
allMoves = ['North','South','East','West']
posMoves = []
for direction in allMoves:
if(self.canMove(direction, curPos)):
posMoves.append(Node(direction, self.getLocIfMove(curPos, direction), 0))
return posMoves
EDIT2 - 分析结果