【发布时间】:2019-10-21 09:33:45
【问题描述】:
给定一个迷宫、起始坐标和结束坐标,
maze = [
[BLACK, BLACK, WHITE, WHITE],
[BLACK, WHITE, WHITE, WHITE],
[WHITE, WHITE, BLACK, WHITE],
[WHITE, WHITE, BLACK, WHITE],
]
s = Coordinate(3, 0)
e = Coordinate(0, 3)
我正在尝试使用 BFS 查找从头到尾的路径。 寻找路径很简单,但我正在努力保持通往目的地的路径。 我试过的是
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
queue = collections.deque()
queue.append(s)
path = []
while queue:
curr = queue.popleft()
if curr == e:
path.append(curr)
return path
path.append(curr)
maze[curr.x][curr.y] = BLACK
for x, y in directions:
new_x, new_y = curr.x + x, curr.y + y
if new_x < 0 or new_y < 0 or new_x >= len(maze) or new_y >= len(maze[0]) or maze[new_x][new_y] == BLACK:
continue
queue.append(Coordinate(new_x, new_y))
类似这样,但结果会打印出我访问过的所有节点,而不是最终路径。关于保持正确路径并删除不属于最终路径的节点的任何提示?
【问题讨论】:
标签: python breadth-first-search