[Python] return path and total weight from graph

Discussão em 'Python' iniciado por Stack, Maio 17, 2025.

  1. Stack

    Stack Membro Participativo

    let us suppose that we have following graph : [​IMG]

    implementation of this graph is done using following code :

    import networkx as nx
    import matplotlib.pyplot as plt
    G =nx.DiGraph()
    edges = [("A", "B", 4), ("A", "C", 2), ("B", "C", 5), ("B", "D", 10),
    ("C", "E", 3), ("E", "D", 4), ("D", "F", 11)]
    G.add_weighted_edges_from(edges)
    pos=nx.spring_layout(G) # pos = nx.nx_agraph.graphviz_layout(G)
    nx.draw_networkx(G,pos)
    labels = nx.get_edge_attributes(G,'weight')
    nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
    plt.show()
    # print(list(nx.all_shortest_paths(G,source='A',target='F')))


    result is : [​IMG]

    from source A to F minimum distance is 20, here is all info about path and their total distances :

    A-B-D-F :4+10+11=25
    A-C-E-D-F :2+3+4+11=20
    A-B-C-E-D-F : 4+5+3+4+11=27


    my question is : how can i show all route and total distance? if we calculate only single route ,we get :

    print(nx.dijkstra_path(G,source='A',target='F'))


    result is :

    ['A', 'C', 'E', 'D', 'F']


    and total distance :

    print(nx.dijkstra_path_length(G,source='A',target='F'))


    result is 20, what about all route from A to F? and their total distance?

    Continue reading...

Compartilhe esta Página