Search code examples
networkx

finding minimal path with networkx where the weights are the nodes


I have a graph in networkx where each node is a number. for example:

import networkx as nx

G = nx.Graph()

G.add_edge(10, 20)

I want to find a minimal patch between two nodes, where the weights are the nodes themselves. Is there a way to do this?


Solution

  • Convert the Graph into a DiGraph (H = G.to_directed()), and assign the weight of each node to all edges originating from that node (for target in H[source]: H[source][target]['weight'] = node_weight). Then you can use path = nx.shortest_path(source, target, weight='weight') as per usual.