简体   繁体   English

PYTHON DFS 无限循环

[英]PYTHON DFS Infinite while loop

Im trying to implement dfs on a matrix but inside my while loop in cases the goal is unreachable it never exists the loop.我试图在矩阵上实现 dfs,但在我的 while 循环中,以防目标无法实现,它从不存在循环。 Any ideas how to tackle that?任何想法如何解决这个问题? Some pointers for the code: RowCol and RowNum have indices of reachable neighbours(ie right, down,right diagonal down)I am adding that to the indices of the current node to get the neighbours indices.代码的一些指针:RowCol 和 RowNum 具有可到达邻居的索引(即向右、向下、向右对角线向下)我将其添加到当前节点的索引以获取邻居索引。 If it's not visited or an obstacle(equal to 1) add it to stack and repeat.如果它未被访问或障碍物(等于 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 :

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM