迭代到递归

时间:2017-12-11 11:51:32

标签: python

大家好,我被困在一项任务上,我想问一个问题。 我的目标是找到启动器(启动)和目标(结束)节点之间的所有可能路径。 我正在研究这段代码及其图表: 注意:字典中的值显示密钥的邻居。     

import sys
graph={'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'], 'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    if start not in graph:
        return None
    paths = []
    for node in graph[start]:
        if node not in path:
            try:
                newpaths = find_all_paths(graph, node, end, path)
                for newpath in newpaths:
                    paths.append(newpath)
            except TypeError:
                print("No road")
                sys.exit()
    return paths

我希望这是一个完全递归的函数(应该没有“for”循环)。我尝试过很多东西,但每次都失败了。 你有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用深度优先搜索来安全地浏览图表。这使用递归并使用marked map避免无限循环:

marked = {}


def navigate(graph):
    v, *tail = graph
    iterate(v, tail) # recursive for loop replacement


def iterate(v, elements):
    if v is not None:
        if v not in marked:
            dfs(graph, v)
        if len(elements) > 0:
            v, *tail = elements
            iterate(v, tail)


def dfs(graph, v):
    print(v)  # do something with the node
    marked[v] = True
    w, *tail = graph[v]
    iterate_edges(w, graph[v])


def iterate_edges(w, elements):
    if w is not None:
        if w not in marked:
            dfs(graph, w)
        if len(elements) > 0:
            v, *tail = elements
            iterate(v, tail)


graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
         'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

navigate(graph)

老实说,我更喜欢带有一些循环的实现,因为那时代码更具可读性:

marked = {}


def navigate(graph):
    for v in graph:
        if v not in marked:
            dfs(graph, v)


def dfs(graph, v):
    print (v)
    marked[v] = True
    for w in graph[v]:
        if w not in marked:
            dfs(graph, w)


graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
         'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}

navigate(graph)

两种变体的输出是:

x1
x2
x4
x5
x7
x9
x3
x6
x8