我有这两个函数来计算二进制网格的 BFS,其中 1 是障碍物,但它无法正常工作。我尝试使用一些打印语句进行调试,并注意到我的队列没有正确填满。在我的 get_neighbors 函数中,我检查给定位置(上、下、左、右)的每个邻居,并将有效选项附加到移动队列中。 “move_count”跟踪 BFS 路径中的总步数,“nodes_left_in_layer”跟踪在进行下一步之前需要从队列中弹出的节点数量,“nodes_in_next_layer”跟踪在 BFS 扩展中添加了多少节点,以便我们可以正确更新“ nodes_left_in_layer”在下一次迭代中。
在使用下面示例网格的 get_neighbors 的第一次迭代中,队列被正确填充为 queue = [(0, 2),(0, 0)]。然而,当 (0, 2) 从队列中弹出时,队列不会被 (1, 2) 填充,即使它是 (2, 0) 中唯一有效的选项。相反,它只是继续并假设无法从 (2, 0) 到达有效位置,然后从队列中弹出 (0, 0) 并检查其邻居。因为已经访问了起始位置并且所有其他邻居都是无效移动,所以它确定从开始到结束没有路径。我很难理解为什么会发生这种情况。
示例:
grid = [[0,0,0],[1, 1, 0],[1, 1, 0]]
start = (0, 1)
goal = (2, 2)
def get_neighbors(grid, current, visited, nodes_in_next_layer, queue):
R = len(grid)
C = len(grid[0])
dr = [-1, 1, 0, 0]
dc = [0, 0, 1, -1]
r = current[0]
c = current[1]
for i in range(4):
rr = r + dr[i]
cc = c + dc[i]
print(rr, cc)
if rr < 0 or cc < 0:
continue
if rr >= R or cc >= C:
continue
if visited[rr][cc]:
continue
if grid[rr][cc] == 1:
continue
#print(rr, cc)
queue.append((rr, cc))
visited[rr][cc] = True
nodes_in_next_layer += 1
def shortest_path_grid(grid, start, goal):
move_count = 0
nodes_left_in_layer = 1
nodes_in_next_layer = 0
done = False
queue = []
visited = [[False] * (len(grid))] * (len(grid))
queue.append(start)
visited[start[0]][start[1]] = True
while size(queue) > 0:
current = queue.pop(0)
#print(current)
if current == goal:
done = True
break
get_neighbors(grid, current, visited, nodes_in_next_layer, queue)
print(queue)
nodes_left_in_layer -= 1
if nodes_left_in_layer == 0:
nodes_left_in_layer = nodes_in_next_layer
nodes_in_next_layer = 0
move_count += 1
if done:
return move_count
return -1