Python 宽度优先搜索错误输出
这是我用来尝试和导航这个迷宫类型的东西的代码,这是我得到的输出Python 宽度优先搜索错误输出,python,breadth-first-search,Python,Breadth First Search,这是我用来尝试和导航这个迷宫类型的东西的代码,这是我得到的输出[(1,1)、(1,2)、(1,3)、(1,4)、(1,5)、(1,6)、(2,6)、(3,6)、(4,6)、(4,5)、(4,4)、(4,3)、(3,3)、(3,2)、(3,1)、(4,1)、(5,1)、(6,1)、(6,3)、(7,3)],而这是我需要的输出[(1,1)、(1,2)、(1,3)、(2,3),(3,3)、(3,2)、(3,1)、(4,1)、(5,1)、(6,1)、(6,2)、(6,3)、(7,3)] 似乎这是打印出所
[(1,1)、(1,2)、(1,3)、(1,4)、(1,5)、(1,6)、(2,6)、(3,6)、(4,6)、(4,5)、(4,4)、(4,3)、(3,3)、(3,2)、(3,1)、(4,1)、(5,1)、(6,1)、(6,3)、(7,3)]
,而这是我需要的输出[(1,1)、(1,2)、(1,3)、(2,3),(3,3)、(3,2)、(3,1)、(4,1)、(5,1)、(6,1)、(6,2)、(6,3)、(7,3)]
似乎这是打印出所有可行走坐标,但我不知道如何解决这个问题,所有在线使用网格的示例都非常关注绘制网格,这会使实际bfs变得混乱。如果将队列视为队列,您将获得所需的输出。这意味着您不会弹出最后一个元素,但不会移出他首先: 替换:
teren = [
'########',
'#s.....#',
'###..#.#',
'#...##.#',
'#.#....#',
'#.####.#',
'#......#',
'###e####'
]
def bfs(teren, start, end):
queue = []
visited = []
queue.append([start])
while queue:
path = queue.pop()
node = path[-1]
x = node[0]
y = node[1]
if node == end:
return path
if node in visited or teren[x][y] == "#":
continue
visited.append(node)
for adjacent in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print(bfs(teren, (1,1), (7, 3)))
与:
或:
但是,它们更适合此类操作:
path = queue.pop(0)
如果将队列视为队列,您将获得所需的输出。这意味着您不会弹出最后一个元素,而是将第一个元素移出: 替换:
teren = [
'########',
'#s.....#',
'###..#.#',
'#...##.#',
'#.#....#',
'#.####.#',
'#......#',
'###e####'
]
def bfs(teren, start, end):
queue = []
visited = []
queue.append([start])
while queue:
path = queue.pop()
node = path[-1]
x = node[0]
y = node[1]
if node == end:
return path
if node in visited or teren[x][y] == "#":
continue
visited.append(node)
for adjacent in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print(bfs(teren, (1,1), (7, 3)))
与:
或:
但是,它们更适合此类操作:
path = queue.pop(0)
您可以打印预期输出吗?它不会输出所有可行走坐标,否。例如,
(2,3)
和(2,4)
可行走,但不包括在路径中。您可以打印预期输出吗?它不会输出所有可行走坐标,否。例如,(2,3)
和(2,4)
可行走,但不包括在路径中。谢谢@AChampion!更新。谢谢@AChampion!更新。
from collections import deque
def bfs(teren, start, end):
queue = deque([])
visited = []
queue.append([start])
while queue:
path = queue.popleft()
# ...etc.