在下面的函数中,“graph”是由1、0和“two”(分别表示障碍物、开阔区域和目标)组成的二维网格列表,“start”是开始搜索的起点。在
def bfs(图形,开始):
fringe = [[start]]
# Special case: start == goal
if start.val == 'g':
return [start]
start.visited = True
# Calculate width and height dynamically. We assume that "graph" is dense.
width = len(graph[0])
height = len(graph)
# List of possible moves: up, down, left, right.
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while fringe:
# Get first path from fringe and extend it by possible moves.
path = fringe.pop(0)
#print path
node = path[-1]
pos = node.pos
# Using moves list (without all those if's with +1, -1 etc.) has huge benefit:
# moving logic is not duplicated. It will save you from many silly errors.
for move in moves:
# Check out of bounds. Note that it's the ONLY place where we check it.
if not (0 <= pos[0] + move[0] < height and 0 <= pos[1] + move[1] < width):
continue
neighbor = graph[pos[0] + move[0]][pos[1] + move[1]]
if neighbor.val == 'g':
return path + [neighbor]
elif neighbor.val == 'o' and not neighbor.visited:
neighbor.visited = True
fringe.append(path + [neighbor]) # creates copy of list
raise Exception('Path not found!')
TRANSLATE = {0: 'o', 1: 'x', 2: 'g'}
graph = [[Node(TRANSLATE[x], (i, j)) for j, x in enumerate(row)] for i, row in enumerate(graph)]
# Find path
path = bfs(graph, graph[4][4])
当我打印path的值时,得到的结果如下:
Path [(4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (3, 8), (2, 8), (1, 8), (1, 9)]
这是x和y坐标。在
现在我如何得到坐标,作为一个单独的'x'和'y'坐标列表?在
我的首选输出是
^{pr2}$当它被打印为“路径”时,显示为“路径”。在
请帮助我,因为我在这一点上陷入了许多搜索,以实现我的首选输出。在
我请求你在这方面给我一些启发。谢谢!!在
你可以用列表理解。在
您可以转置元组并将其映射到列表,或者使用map和itemgetter。在
您需要在类中添加
^{pr2}$iter
,以便可以迭代对象:对于
bfs
,使用Queue将是一个有效的解决方案:相关问题 更多 >
编程相关推荐