将递归转换为迭代到循环

时间:2016-12-04 04:58:33

标签: python python-3.x

我正试图找出一种方法,使用某种形式的循环而不是递归将最顶层函数的最后一行转换为迭代。我现在真的很难过,我想知道你们有没有人可以提供帮助。它是一个创建的函数,用于搜索使用深度优先遍历的有向图中是否存在给定的起点和终点路径。

def helper(graph, current, visited):
    if current in graph:
        for neighbor in graph[current]:
            if neighbor not in visited:
                visited.append( neighbor )
                helper(graph, neighbor, visited)

def DFS(graph, start, goal):
    if start not in graph and goal not in graph:
        return False
    visited = [start]
    helper(graph, start, visited)
    return goal in visited

0 个答案:

没有答案