我使用的是python3和networkx1.11。在
我做了一个加权图,在边上和一些节点上有权重,但是当我计算最短路径的权重时,没有考虑节点的权重(代码如下)。在
有人知道如何确保节点权重被考虑在内吗?在
谢谢!
山姆import networkx as nx
from matplotlib import pyplot as plt
# Set up a station map
all_stations = ['a','b','c','d','e']
interchange_stations = ['b']
routes = {'a':{'b':2}, 'c':{'b':2}, 'b':{'d':2}, 'd':{'e':2}}
print(routes)
# Make a network graph
G = nx.Graph()
# Add all the nodes (stations)
for station in all_stations:
weight = 0
if station in interchange_stations:
weight = 5
G.add_node(station, weight=weight)
print(G.nodes(data=True))
# Iterate through each line and add the time between stations
for name1, value in routes.items():
for name2, time in value.items():
if name1 == name2:
continue
G.add_edge(name1, name2, weight=time)
print(G.edges(data=True))
# Work out the minimium distance between all stops
route_times = nx.all_pairs_dijkstra_path_length(G)
# Work out the minimum path between all stops
route = nx.all_pairs_dijkstra_path(G)
print(route['a']['e']) # Returns: ['a', 'b', 'd', 'e']
print(route_times['a']['e']) # Returns: 6 (should be 2+2+2+5)