Python深度优先搜索非递归方法

Python深度优先搜索非递归方法,python,data-structures,graph,depth-first-search,Python,Data Structures,Graph,Depth First Search,我已经使用递归方法实现了DFS。然而,我的程序在执行后立即中断 # Non Recursive approach def Non_Recursive_dfs(graph, source): path = [] stack = [] stack.append(source) while stack: s = stack.pop() if s not in path: path.append(s)

我已经使用递归方法实现了DFS。然而,我的程序在执行后立即中断

# Non Recursive approach
def Non_Recursive_dfs(graph, source):
    path = []
    stack = []
    stack.append(source)
    
    while stack:
        s = stack.pop()
        if s not in path:
            path.append(s)

        if s in path:
            #leaf node
            continue
        for neighbour in graph[s]:
            stack.append(neighbour)
    
    return " ".join(path)
输入和输出:

print(Non_Recursive_dfs(graph, "A"))
O/p: A

有人能解释为什么会发生这种情况吗?

第一个
if
语句保证第二个语句下的代码将始终执行,因为它将
s
添加到
路径中(如果它不在路径中)。您只需将第二个
if
语句更改为
else if
语句,如下所示:

def Non_Recursive_dfs(graph, source):
    path = []
    stack = []
    stack.append(source)
    
    while stack:
        s = stack.pop()
        if s not in path:
            path.append(s)

        elif s in path:
            #leaf node
            continue
        for neighbour in graph[s]:
            stack.append(neighbour)
    
    return " ".join(path)

我很快为
graph
创建了一些虚拟数据,它似乎运行得很好。

第一个
if
语句保证第二个语句下的代码将始终执行,因为它将
s
添加到
path
,如果它不在其中。您只需将第二个
if
语句更改为
else if
语句,如下所示:

def Non_Recursive_dfs(graph, source):
    path = []
    stack = []
    stack.append(source)
    
    while stack:
        s = stack.pop()
        if s not in path:
            path.append(s)

        elif s in path:
            #leaf node
            continue
        for neighbour in graph[s]:
            stack.append(neighbour)
    
    return " ".join(path)

我很快为
graph
创建了一些虚拟数据,它似乎运行得很好。

如果路径中没有if语句,那么第一条if语句会附加到路径中。这保证了第二条if语句下的代码将始终被执行。如果路径中没有第一条if语句,则会将它追加到路径中。这保证了第二条if语句下的代码将始终被执行。