我正努力在布洛克索兹游戏中实现一个星型算法.目标是用1x1x2块到达终点。我实现了这个算法,但是它不一致。有时它不能给出最短的解。例如:
maze = ['00011111110000',
'00011111110000',
'11110000011100',
'11100000001100',
'11100000001100',
'1S100111111111',
'11100111111111',
'000001E1001111',
'00000111001111']对于这个迷宫,我的实现给出了以下结果:
U,L,U,R,R,U,R,R,D,L,D,R,D,L,U,R,U,L,D,R,D,L,D,R,U,L,D,R,D,L,D,R,D,D,L,D,R,D,L,D,L,D,
有29个动作。但有一个较短的解决方案,其中有28个步骤:
U,L,U,R,R,U,R,D,D,R,U,L,D
这是我的实现,完整的代码是这里,我能为它做些什么?
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))发布于 2021-12-12 12:45:38
假设您的实现中的其他一切都是正确的,这只是因为您的启发式是不可接受的。
考虑一下迷宫:
B 1 1 X你可以在两个动作中达到目标:
1 B B X : move1
1 1 1 B : move2但是你的启发暗示它至少需要3步。
max(abs(current.x2 - end.x1), abs(current.y2 - end.y1))
= max(abs(0-3), abs(0-0)) = max(3, 0) = 3启发式函数不能高估A*总是给出最优路径的到达目标所需的移动次数,因为这样做可能在到达目标时留下一个潜在的最优路径未被探索(最优路径可能从未被扩展,因为它的成本被h(N)高估)。
您需要一个启发式,它考虑到给定的坐标在任何给定的移动中最多可以改变2(当一个块从站立到说谎,反之亦然)。为此,您可以将当前启发式函数的结果除以2。
def get_heuristic(current:Node, end:Node) -> int:
return 1/2 * max(abs(current.x2 - end.x1), abs(current.y2 - end.y1))这给出了长度28路径ULURRURRRRRRDRDDDDDRULLLLLLD。
发布于 2021-12-12 13:08:22
正如间接说的那样,问题是关于启发式函数的。间接的回答不是直接起作用,而是给了我一些想法,我想出了这个方法。
return 1/4 * max(max(abs(current.x1 - end.x1), abs(current.y1 - end.y1)), max(abs(current.x2 - end.x2), abs(current.y2 - end.y2)))由于可能有两个点定位块,我应该选择x1和x2的最大差值,从端点选择y1和y2,而不是选择最大值,乘以1/4,因为它是从4个点中选择的。
https://stackoverflow.com/questions/70318318
复制相似问题