PYTHON DFS无限while循环



我试图在矩阵上实现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 :

最新更新