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

时间:2014-01-01 17:13:26

标签: python-3.x graph directed-graph

简单问题: G是带边

的有向图
a->b
a->c
c->d

它存储在Python字典

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

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

1 个答案:

答案 0 :(得分:4)

Straight from 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)))

产量

a -> b: ['a', 'b']
a -> c: ['a', 'c']
a -> d: ['a', 'c', 'd']
b -> c: None
b -> d: None
c -> d: ['c', 'd']

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