在Networkx MultiDigraph上找到路径

时间:2019-02-09 01:45:02

标签: python graph networkx breadth-first-search

我有这样的MultiDigraph

G=nx.MultiDiGraph()

G.add_edge(1,2,attr=0.5)
G.add_edge(3,2,attr=1.0)

我正在尝试找到从节点1到节点3的路径,它将提供如下结果:

1 to 2 (forward), 2 to 3 (reverse). 

任何Networkx方式可以做到吗?谢谢,

2 个答案:

答案 0 :(得分:1)

您可以创建图形的无向版本,然后在此处检查路径。然后返回到有向图,以查看是否必须沿特定边向后走:

Gu = G.to_undirected()
path = nx.shortest_path(Gu, source=1, target=3)

# Go through each edge in the path to check if it's "forward"
for x in range(len(path)-1):
    if G.has_edge(path[x], path[x+1]):
        print(f'{path[x]} to {path[x+1]} (forward)')
    elif G.has_edge(path[x+1], path[x]):
        print(f'{path[x]} to {path[x+1]} (reverse)')
    else:
        # This shouldn't happen but always good to check
        print(f'No path from {path[x]} to {path[x+1]}')

答案 1 :(得分:0)

您可以找到无向G的路径,然后获取所有边,这些边将构建无向G的路径,并检查这些边是否在由路径节点alter table my_current_Table add columns(load_date string); insert overwrite table my_current_Table select t.*, date_format(current_timestamp,'yyyyMMdd HH:mm:ss') as load_date from my_current_Table t; 与{{1 }}:

[(1, 2), (2, 3)]