【问题标题】:Shortest-Path Search - using Edge types [NetworkX, igraph]最短路径搜索 - 使用边缘类型 [NetworkX, igraph]
【发布时间】:2015-04-06 10:14:03
【问题描述】:

我使用 Directed MultiGraph 作为数据结构(两个节点之间可能不止一条边)。

我想在我的 MultiDiGraph 中分配不同类型的边。比如边(u,v_1)可以是type_1,另外一条边(u,v_2)可以是type 2。

构建此数据结构后,我想找到最短路径,但路径必须仅包含特定类型的边(例如类型 1)。 NetworkX 或 python-igraph 库中是否有可能?

【问题讨论】:

  • 在igraph中,根据类型设置边的权重。 IE。将所有类型 1 的边权重设置为 1,将所有其他边权重设置为无穷大。

标签: python graph igraph networkx shortest-path


【解决方案1】:

正如@Gabor Csardi in networkx 所建议的,添加类型1的边:添加属性type_1与您想要的值,并将属性type_2添加到最大int(在最短路径计算中被忽略,就好像它不存在一样)。同样,创建 type_2 的边。

下面的代码显示了一个简单的图表来表明从 1 到 4 的最短路径在 type_1 边中通过 2 更短,在 type_2 边中通过 3 更短。

g=nx.MultiDiGraph()
g.add_edge(1,2,type1=2,type2=sys.maxint) # add edge of type 1 
g.add_edge(1,2,type1=sys.maxint,type2=3) # add edge of type 2
g.add_edge(2,4,type1=2,type2=sys.maxint)
g.add_edge(2,4,type1=sys.maxint,type2=4)
g.add_edge(3,4,type1=3,edge_type2=sys.maxint)
g.add_edge(3,4,type1=sys.maxint,type2=1)
g.add_edge(1,3,type1=sys.maxint,type2=1)
print nx.shortest_path(g,1,4,weight='type1')
print nx.shortest_path(g,1,4,weight='type2')

结果:

[1, 2, 4]
[1, 3, 4]

另外,请找到所创建的图表,以便更容易地对其进行可视化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多