用Stack实现深度有限路径查找

时间:2016-02-08 01:27:08

标签: python search depth-first-search

嘿喜欢标题说我正在尝试在Python3中实现深度限制搜索,它返回给定图形,起始顶点和目标顶点的路径。我正在努力解决如何强制执行搜索限制的问题。到目前为止,我有:

def dfs(g, v, goal, limit=-1):

    SENTINEL = object()    
    visitedStack = [v]
    path = ""

    while visitedStack:
        currentVertex = visitedStack.pop()    

        if g.getVertex(currentVertex) != None:
            if g.getVertex(currentVertex).visited == False:
                path += currentVertex + ' -> '

                g.getVertex(currentVertex).hasBeenVisited()

                if currentVertex == goal: 
                    return path[:-3]

                elif currentVertex == SENTINEL:
                    limit += 1

                elif limit != 0:
                    limit -= 1
                    visitedStack.append(SENTINEL)
                    visitedStack.extend(g.getVertex(currentVertex).getConnections()) 

     return "Depth limit was reached"

编辑:我更改了一些代码以检查访问过的顶点。编辑后,返回的搜索有时无法正常工作。例如,我将深度限制设置为3,但返回的路径为4或5。其他时候我会将限制设置为7并返回“达到限制”。注意:最小路径为3

1 个答案:

答案 0 :(得分:1)

当搜索进入更深层次时,将哨兵推入堆栈并减少限制。当您从堆栈中弹出一个标记时,会增加该级别。

def dfs_limit(g, start, goal, limit=-1):
    '''
    Perform depth first search of graph g.
    if limit >= 0, that is the maximum depth of the search.
    '''
    SENTINEL = object()
    visitedStack = [start]
    path = []

    while visitedStack:
        currentVertex = visitedStack.pop()

        if currentVertex == goal: 
            path.append(currentVertex)
            return ' -> '.join(path)

        elif currentVertex == SENTINEL:
            #finished this level; go back up one level
            limit += 1
            path.pop()

        elif limit != 0:
            # go one level deeper, push sentinel
            limit -= 1
            path.append(currentVertex)
            visitedStack.append(SENTINEL)
            visitedStack.extend(g.getVertex(currentVertex).getConnections())

如果图表中有循环或多条路线,您还需要跟踪已访问过的节点,这样您就不会重复工作或进入无限循环。