找到Python深度优先搜索后停止

问题描述

我对此有疑问。当所搜索区域的上述坐标的网格状态== 5时,将停止并移至该位置。由于某种原因,它还在继续,我一直在尝试找出原因。我认为在别人的注视下这将是显而易见的事情!

def depthfirstsearch(visited,graph,vertex):
    # Do a depth-first search of all neighbours if found stop.
    moveto(vertex,3)
    visited.append(vertex)
    if (the_maze.grid[vertex[0] - 1][vertex[1]].status) == 5:
        x = vertex[0] - 1
        y = vertex[1]
        moveto((x,y),0)
        return
    else:
        for neighbour in graph[vertex]:
            if neighbour not in visited:
                depthfirstsearch(visited,neighbour)

解决方法

您的函数在找到目标时返回。

if (the_maze.grid[vertex[0] - 1][vertex[1]].status) == 5:
    # ..
    return

但是,它返回None并且递归调用对返回的事实不做任何事情:

if neighbour not in visited:
    depthfirstsearch(visited,graph,neighbour)

如果对depthfirstsearch()的调用找到了目标,则您希望函数也返回,并得到肯定的结果。如果找不到电话,则希望它继续搜索。

因此,您需要:

if (the_maze.grid[vertex[0] - 1][vertex[1]].status) == 5:
    # ..
    return True

并且:

if neighbour not in visited:
    if depthfirstsearch(visited,neighbour):
        return True

最后,您可以依靠仅在完成时返回None而不显式返回的函数,但这有点难看。 None的计算结果为False,而bool则为return False,但是为了清楚起见和类型安全,您也可以只def depthfirstsearch(visited,vertex): # Do a depth-first search of all neighbours if found stop. moveto(vertex,3) visited.append(vertex) if (the_maze.grid[vertex[0] - 1][vertex[1]].status) == 5: x = vertex[0] - 1 y = vertex[1] moveto((x,y),0) # found it,report success return True else: for neighbour in graph[vertex]: if neighbour not in visited: if depthfirstsearch(visited,neighbour): # found in recursion,report success return True # if this point is reached,this call didn't find it anywhere return False 结尾。

因此,结果:

@media (min-width: 768px)