【发布时间】:2019-06-17 16:11:09
【问题描述】:
我在 Python 3 中使用 Networkx 的 floyd_warshall_predecessor_and_distance 函数来查找双向图上的最短路径。该函数返回给定两个节点(如果存在边)和路径的一部分之间的最短距离。我将澄清我所说的“一部分”的意思。以下是我的输入和输出。
输入:
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
V = [1, 2, 3, 4, 5]
N = [(i,j) for i in V for j in V if i!=j]
E = {} #Creating an empty dictionary to store the travel times from node i to j
Elist = (list(np.random.randint(low=1, high = 30, size = len(N))))
for i in range(len(N)):
E[N[i]] = Elist[i] # (i,j) does not have to be equal to (j,i)
E[(2, 1)] = 5
E[(5, 4)] = 0
E[(2, 4)] = 20
G=nx.DiGraph()
G.add_nodes_from(V)
for i in E:
G.add_weighted_edges_from([(i[0], i[1], E[i])])
path_lengths=nx.floyd_warshall_predecessor_and_distance(G, weight='weight')
path_lengths
输出:
({1: {2: 1, 3: 4, 4: 5, 5: 1},
2: {1: 2, 3: 4, 4: 5, 5: 1},
3: {1: 3, 2: 3, 4: 5, 5: 1},
4: {1: 4, 2: 1, 3: 4, 5: 1},
5: {1: 4, 2: 5, 3: 4, 4: 5}},
{1: defaultdict(<function networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda>()>,
{1: 0, 2: 13, 3: 8, 4: 1, 5: 1}),
2: defaultdict(<function networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda>()>,
{2: 0, 1: 5, 3: 13, 4: 6, 5: 6}),
3: defaultdict(<function networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda>()>,
{3: 0, 1: 10, 2: 20, 4: 11, 5: 11}),
4: defaultdict(<function networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda>()>,
{4: 0, 1: 5, 2: 18, 3: 7, 5: 6}),
5: defaultdict(<function networkx.algorithms.shortest_paths.dense.floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda>()>,
{5: 0, 1: 5, 2: 13, 3: 7, 4: 0})})
我故意为 (2, 4) 创建了一条路径,即 2 > 1 > 5 > 4。当我查看 path_lengths[0] 时,我可以看到从节点 2 到 4,我停在了 5 处。进一步,从 2 到 5,我停在 1。这两个告诉我完整的路线,但我想看到整个路线作为输出,例如,2: {... 4: 1, 5, ...} 或 {(2,4): (2,1), (1,5), (5,4)},而不是看到它的一部分,然后结合脑海中的碎片。 Networkx 中是否有更好的软件包可以做到这一点?顺便说一句,我的双向图不涉及负权重,而且图可以很大(这就是我选择这个函数的原因)。
这是我的尝试:
new = path_lengths[0]
for v in V:
for d in V:
if v!=d:
if new[v][d] != v:
new[v][d] = (new[v][d],d)
elif new[v][d] == v:
new[v][d] = (v,d)
感谢您的回复!
【问题讨论】:
标签: python-3.x graph networkx bidirectional