[Python图论]在用图nx.shortest_path求解最短路径时,节点之间有多条边edge,会如何处理?

问: 在使用图求最短路径时,如果节点之间有多条路径,shortest_route = nx.shortest_path(G, source=start_node, target=end_node, weight='length')会如何处理,会自动选择最短那条吗?

python 复制代码
# 输出图G各节点之间有多少条边edge,并给出其长度
Edges between 103928 and 25508583:共2条
Edge: 103928 -> 25508583, Key: 0, Length: 77.277
Edge: 103928 -> 25508583, Key: 1, Length: 112.16900000000001
Edges between 26630792 and 5521427550:共2条
Edge: 26630792 -> 5521427550, Key: 0, Length: 85.091
Edge: 26630792 -> 5521427550, Key: 1, Length: 88.07600000000001
Edges between 107876 and 107873:共2条
Edge: 107876 -> 107873, Key: 0, Length: 83.102
Edge: 107876 -> 107873, Key: 1, Length: 186.669

答:是的,nx.shortest_path 会自动选择权重最小的那条路径。

当你在 NetworkX 中使用 nx.shortest_path(G, source=start_node, target=end_node, weight='length') 时,它会根据你指定的权重(在这个例子中是 'length')找到源节点和目标节点之间权重最小的路径。

对于节点之间有多条路径的情况,NetworkX 会如下处理:

  • 如果两个节点之间有多条路径,例如 (u, v),NetworkX 会选择所有可能的路径,并根据你指定的权重属性(在这个例子中是 length)找到最小权重的路径。
  • 在你的例子中,每一对节点之间都有两条路径。NetworkX 会比较这两条路径的 length 属性,并选择长度最短的那条路径作为该节点对之间的最短路径。
  • 这个过程会在整个图上进行,直到找到从起点到终点的全局最短路径。

具体示例

以你的数据为例:

  1. 节点 103928 -> 25508583:

    • 第一条路径长度:77.277
    • 第二条路径长度:112.169
    • NetworkX 选择:77.277 长度的路径(Key: 0)
  2. 节点 26630792 -> 5521427550:

    • 第一条路径长度:85.091
    • 第二条路径长度:88.076
    • NetworkX 选择:85.091 长度的路径(Key: 0)
  3. 节点 107876 -> 107873:

    • 第一条路径长度:83.102
    • 第二条路径长度:186.669
    • NetworkX 选择:83.102 长度的路径(Key: 0)
  4. 节点 11767210 -> 12026764:

    • 第一条路径长度:219.545
    • 第二条路径长度:95.666
    • NetworkX 选择:95.666 长度的路径(Key: 1)

总结

  • NetworkX 的 shortest_path 函数会自动为你选择每对节点之间权重最小的路径。
  • 因此,你不需要手动指定哪条路径是最短的,NetworkX 会基于权重(如 length)自动做出选择。

输出图内各节点之间的边及其长度 代码:

python 复制代码
# 输出图内各节点之间的边及其长度

import networkx as nx


# Get all the nodes in the graph
nodes = G.nodes()

# Iterate over all pairs of nodes
for u in nodes:
    for v in nodes:
        # Skip if u and v are the same node
        if u == v:
            continue

        # Get the edges between u and v
        edges = G.get_edge_data(u, v)
        
        # If there are no edges between u and v, skip to the next pair of nodes
        if edges is None:
            continue
        edges_count = len(edges.items())
        if edges_count >1:
          # Print the edges and their lengths
          print(f"Edges between {u} and {v}:共{edges_count}条")
          for key, data in edges.items():
              print(f"Edge: {u} -> {v}, Key: {key}, Length: {data['length']}")
相关推荐
多恩Stone9 分钟前
【3DV 进阶-5】3D生成中 Inductive Bias (归纳偏置)的技术路线图
人工智能·python·算法·3d·aigc
闲人编程22 分钟前
使用Python进行量化交易入门
开发语言·python·统计分析·lambda·量化·codecapsule
长颈鹿仙女2 小时前
发送 Prompt 指令:判断用户评价是好评还是差评
python·大模型
小兔崽子去哪了2 小时前
PyMySQL 笔记
python
景彡先生2 小时前
Python NumPy广播机制详解:从原理到实战,数组运算的“隐形翅膀”
开发语言·python·numpy
咕白m6253 小时前
Python 查找高亮 Excel 指定数据
python
倦王3 小时前
PyTorch图片数据载入方法
人工智能·pytorch·python
岑梓铭4 小时前
《考研408数据结构》第七章(6.1~6.3图的概念、存储方式、深/广度遍历)复习笔记
数据结构·笔记·考研·算法·图论·408·ds
用户617433273104 小时前
Python 的 with ... as ... 上下文管理器
python