[Python] Is there a graph-tool function that gives all the shortest paths for weighted...

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working with a weighted undirected graph in graph_tool and would like to find all shortest paths between two nodes. I initially tried passing a dist_map to all_shortest_paths(), but after reading the documentation more carefully, I realized that this approach doesn't work as I expected.

    Is there a simple or idiomatic way to get all shortest paths in a weighted graph using graph_tool? I feel like I might be missing something obvious. Here is an example:

    import graph_tool.all as gt

    g = gt.Graph({0: [1,2], 1:[4], 2:[3],3:[4]}, directed=False)
    edge_weights = g.new_edge_property("float", 0)
    edge_weights[g.edge(0,1)] = 20

    source_node = g.vertex(0)
    target_node = g.vertex(4)

    full_dist_map = gt.shortest_distance(g, source=source_node, weights=edge_weights)

    print("\nFinding all shortest weighted paths using all_shortest_paths:")
    weighted_shortest_paths_generator = gt.all_shortest_paths(g, source=source_node, target=target_node, dist_map=full_dist_map)
    for path in weighted_shortest_paths_generator:
    print(path) # Would like to have [0, 2, 3, 4]

    print("\nFinding one shortest weighted path using shortest_path:")
    path_vertices, _ = gt.shortest_path(g, source=source_node, target=target_node, weights=edge_weights)
    print([int(v) for v in path_vertices]) # Should print [0, 2, 3, 4]


    Output:

    Finding all shortest weighted paths using all_shortest_paths:
    [0 1 4]

    Finding one shortest weighted path using shortest_path:
    [0, 2, 3, 4]

    Continue reading...

Compartilhe esta Página