问题描述
如果有一条路径,我将返回最短路径的长度.否则,我返回-1.
I am returning the length of the shortest path if there's is one. Otherwise, I return -1.
我正在尝试以这样的方式打印矩阵,使所有属于最短路径的访问节点都标记为"$"而不是"1".但是,我无法这样做.
I'm trying to print the matrix in such a way that all visited nodes that were a part of the shortest path are marked with '$' instead of '1'. However, I'm not able to do so.
def Path(grid):
#print(grid)
start = (0, 0)
queue = collections.deque([[start]])
seen = set([start])
while queue:
path = queue.popleft()
x, y = path[-1]
if y == 7 and x == 7:
#print(path)
for (i, j) in path:
grid[i][j] = '$'
print(grid)
return len(path)
for x2, y2 in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1):
if (grid[y2][x2] != 0) and (x2, y2) not in seen:
queue.append(path + [(x2, y2)])
seen.add((x2, y2))
print(grid)
return -1
推荐答案
问题出在如何处理网格
:
寻找下一个可用动作时,请执行以下测试:
When looking for the next available move, you do this test:
grid[y2][x2] != 0
其中(x2,y2)
可能会添加到路径中.
where (x2, y2)
is potentially added to the path.
但是当您最终分配 $
时,您会写:
But when you finally assign the $
, you write:
grid[i][j] = '$'
其中(i,j)
是从路径中提取的元组.
where (i, j)
is the tuple taken from the path.
这是不一致的.您应该在两个 grid [] []
表达式之一中交换坐标位置,以使它们一致.
This is not consistent. You should swap the coordinate position in one of the two grid[][]
expressions to make them consistent.
这篇关于确定矩阵游戏中的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!