[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']}")
相关推荐
databook8 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar9 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户83562907805110 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_10 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机16 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机17 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机17 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机17 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i18 小时前
drf初步梳理
python·django
每日AI新事件18 小时前
python的异步函数
python