【发布时间】:2022-01-15 23:03:50
【问题描述】:
我正在努力在 Bloxorz 游戏上实现 a-Star 算法。目标是使用 1 x 1 x 2 块到达终点。我实现了算法,但它不一致。有时它不会给出最短的解决方案。例如:
maze = ['00011111110000',
'00011111110000',
'11110000011100',
'11100000001100',
'11100000001100',
'1S100111111111',
'11100111111111',
'000001E1001111',
'00000111001111']
对于这个迷宫,我的实现给出了这样的结果:
U,L,U,R,R,U,R,R,R,R,R,R,D,R,D,D,D,L,L,L,D,R,D,L ,U,R,U,L,D
有 29 步。但是有一个较短的解决方案,它有 28 步:
U,L,U,R,R,U,R,R,R,R,R,R,D,R,D,D,D,D,D,R,U,L,L,L ,L,L,L,D
这是我的实现,完整代码是here,我能做些什么呢?
class Node:
def __init__(self,parent:'Node', node_type:str, x1:int, y1:int, x2:int, y2:int, direction:str=''):
self.parent = parent
self.node_type = node_type
self.g = 0
self.h = 0
self.f = 0
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.visited = False
self.direction = direction
def get_positions(self) -> tuple:
return (self.x1, self.y1, self.x2, self.y2)
def __eq__(self, other):
if type(other) is Node:
return self.x1 == other.x1 and self.y1 == other.y1 and self.x2 == other.x2 and self.y2 == other.y2
elif type(other) is tuple:
return self.x1 == other[0] and self.y1 == other[1] and self.x2 == other[2] and self.y2 == other[3]
else:
return False
def __lt__(self, other:'Node'):
return self.f < other.f
def aStar(start:Node, end:Node, grid:List[List[str]]) -> List[tuple]:
open_list = []
closed_list = []
heapq.heappush(open_list, start)
while open_list:
current:Node = heapq.heappop(open_list)
if current == end:
return reconstruct_path(current)
closed_list.append(current)
for neighbor in get_neighbors(current, grid):
if neighbor not in closed_list:
neighbor.g = current.g + 1
neighbor.h = get_heuristic(neighbor, end)
neighbor.f = neighbor.g + neighbor.h
if neighbor not in open_list:
heapq.heappush(open_list, neighbor)
return []
def reconstruct_path(current:Node) -> List[tuple]:
path = []
while current.parent is not None:
path.append(current.direction)
current = current.parent
return ''.join(path[::-1])
def get_heuristic(current:Node, end:Node) -> int:
return max(abs(current.x2 - end.x1), abs(current.y2 - end.y1))
【问题讨论】:
标签: python python-3.x algorithm shortest-path a-star