问题描述
我正在尝试在矩阵上实现dfs,但在目标循环无法实现的情况下,在我的while循环内,它永远不会存在。 任何想法如何解决? 该代码的一些指针: RowCol和RowNum具有可到达的邻居的索引(即右,下,右对角线向下)我将其添加到当前节点的索引中以获取邻居索引。如果没有被访问或有障碍物(等于1),请将其堆叠并重复。
while stack:
curr = stack.get() # Dequeue the front cell
path.append(curr.pt)
# If we have reached the destination cell,# we are done
pt = curr.pt
if pt == goal:
print("Sequence : ")
print(path)
print("Path : ")
print(curr.path+" to "+str(pt))
return curr.dist
# Otherwise enqueue its adjacent cells
for i in range(3):
if i == 0 or i == 1:
cost = 2
elif i == 2:
cost = 3
row = pt[0] + rowNum[i]
col = pt[1] + colNum[i]
# if adjacent cell is valid,has path
# and not visited yet,enqueue it.
if isValid(row,col):
if matrix[row][col] == "0" and not visited[row][col]:
visited[row][col] = True
Adjcell = queueNode([row,col],curr.dist + cost,curr.path+" to "+str(curr.pt))
stack.put(Adjcell)
# Return -1 if destination cannot be reached
print(matrix[start[0]][start[1]])
print(matrix[goal[0]][goal[1]])
print("Can't reach goal")
return -1
解决方法
如果要循环使用
while True :