python - 为什么这个图形路由会重复

标签 python python-3.x algorithm graph-databases

我一直在学习 Python 中的图形算法,并且想知道为什么我在结果中得到了重复的路径。

这是我的代码

from collections import defaultdict

our_graph = defaultdict(list)


def run_graph():
    print('Creating Graph...')
    add_edges("London", "Barcelona")
    add_edges("Barcelona", "Madrid")
    add_edges("Madrid", "Ottawa")
    add_edges("Madrid", "Berlin")
    add_edges("London", "Ottawa")

    print('\nOur Graph:')
    print(our_graph)

    print('\nEdges:')
    print(list_edges())

    print('\nTesting Paths To Invalid Nodes:')
    print(find_all_paths("LDN", "Ottawa"))
    print(find_all_paths("London", "X"))

    print('\nTesting Paths To Valid Nodes:')
    print(find_all_paths("London", "Ottawa"))
    print('---')
    print(find_all_paths("London", "Berlin"))


def add_edges(a, b):
    our_graph[a].append(b)
    our_graph[b].append(a)


def list_edges():
    edges = []
    for node in our_graph:
        for next_node in our_graph[node]:
            edges.append((node, next_node))
    return edges


def find_all_paths(start, end, path=[]):
    # If there isn't a node with that name
    if our_graph[start] == [] or our_graph[end] == []:
        return 'Can\'t find nodes ' + start + " " + end
    else:
        # create a path
        path = path + [start]
        # If start node is the end
        if start == end:
            return [path]
        paths = []
        newpaths = []
        # For each node
        for node in our_graph[start]:
            # If node not already in saved path
            if node not in path:
                # Search the paths of that new node
                newpaths = find_all_paths(node, end, path)
            # Append new path to paths
            for newpath in newpaths:
                paths.append(newpath)
        return paths


if __name__ == '__main__':
    run_graph()

我从 print(find_all_paths("London", "Berlin")) 得到的结果

[['London', 'Barcelona', 'Madrid', 'Berlin'], ['London', 'Ottawa', 'Madrid', 'Berlin'], ['London', 'Ottawa', 'Madrid', 'Berlin']]

如您所见,伦敦-渥太华-马德里-柏林的路线重复了。你能解释一下为什么吗?

最佳答案

问题出在这里:

if node not in path:
    # Search the paths of that new node
    newpaths = find_all_paths(node, end, path)
# Append new path to paths
for newpath in newpaths:
    paths.append(newpath)

如果 node 已经在 path 中,将使用旧的 newpaths。您只需要将 for 循环移动到 if 语句下即可:

if node not in path:
    # Search the paths of that new node
    newpaths = find_all_paths(node, end, path)
    # Append new path to paths
    for newpath in newpaths:
        paths.append(newpath)

或:

if node not in path:
    # Search the paths of that new node
    paths += find_all_paths(node, end, path)

此外,我建议使用 defaultdict(set) 而不是列表。

关于python - 为什么这个图形路由会重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57794766/

相关文章:

python-3.x - 如何使用dlib获取眼睛和嘴巴的长度

algorithm - 如何用汇编语言打印 0,2,4,6,...?

python - 使用 Python 中的 30 年基线计算气候异常

python - 表达式中间的增强赋值导致 SyntaxError

python - 使用 pip 在 Windows 10 上安装 Jupyter 时出错

python - Seaborn jointplot 十六进制选项不生成图形

javascript - 有效地将线段排序成一个循环

algorithm - 就范围大小而言,调用 get(Range) 的大 O 性能是什么?为什么?

python - Python有没有像R中的quantmod一样可以下载财务报表数据的类似库?

python - 用pytables压缩数组