簡體   English   中英

Python:有向圖中節點之間的路徑

[英]Python: path between nodes in directed graph

一個簡單的問題:G是有邊的有向圖

a->b
a->c
c->d

它存儲在Python字典中

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

我想要a和d之間的路徑,d和a之間的路徑,b和d之間的路徑等。

從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軟件包感興趣。

暫無
暫無

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

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