Python:有向图中节点之间的路径

0 graph directed-graph python-3.x

简单问题:G 是带边的有向图

a->b
a->c
c->d
Run Code Online (Sandbox Code Playgroud)

它存储在 Python 字典中

G={'a':['b','c'], c:['d']}
Run Code Online (Sandbox Code Playgroud)

我想要a和d之间的路径,d和a之间的路径,b和d之间的路径等等。

unu*_*tbu 5

直接从 Guido van Rossum发给您:

import collections
import itertools as IT

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

G={'a':['b','c'], 'c':['d']}

for node1, node2 in IT.combinations(list('abcd'), 2):
    print('{} -> {}: {}'.format(node1, node2, find_shortest_path(G, node1, node2)))
Run Code Online (Sandbox Code Playgroud)

产量

a -> b: ['a', 'b']
a -> c: ['a', 'c']
a -> d: ['a', 'c', 'd']
b -> c: None
b -> d: None
c -> d: ['c', 'd']
Run Code Online (Sandbox Code Playgroud)

您可能还对networkxigraphgraph-tool包感兴趣。