簡體   English   中英

迭代到遞歸

[英]Iterative into Recursive

大家好,我忙於做作業,想問一個問題。 我的目標是找到starter(start)和target(end)節點之間的所有可能路由。 我正在研究此代碼及其圖形: 注意:字典中的值顯示鍵的鄰居。

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”循環)。我嘗試了很多事情,但是每次都失敗了。 你有什么建議嗎?

您可以使用深度優先搜索來安全地瀏覽圖形。 這使用了遞歸,並避免了使用marked映射的無限循環:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM