Skip to content

shortest_path

Syntax

shortest_path(network, source_node_id, dest_node_id)

Parameters

network
The network in which to find the path.
source_node_id
The ID of the source node to start from.
dest_node_id
The ID of the destination node to end on.

Description

Using Dijkstra’s algorithm, returns a list of nodes in the network from source to destination with the shortest total edge weights. Returns an empty list if either node is not in the network, or if there is no path from source to destination.

Examples

simulation {
    locations = none
    default_model = none
    start_date = 2020-Jan-01
    end_date = 2020-Jan-02
}

variables {
    shared list weights
    shared list path
    shared list n
    shared numeric i
    shared numeric path_length
}

network my_undirected_network {
    is_directed = 0
}

startup {
    add_edge(my_undirected_network, 1, 2)
    add_edge(my_undirected_network, 2, 3)
    add_edge(my_undirected_network, 3, 4)
    add_edge(my_undirected_network, 4, 5)
    add_edge(my_undirected_network, 5, 6)
    add_edge(my_undirected_network, 6, 1)

    set_weight(my_undirected_network, 1, 2, 10)
    set_weight(my_undirected_network, 2, 3, 10)
    set_weight(my_undirected_network, 3, 4, 10)
    set_weight(my_undirected_network, 4, 5, 10)
    set_weight(my_undirected_network, 5, 6, 10)
    set_weight(my_undirected_network, 6, 1, 10)

    path = shortest_path(my_undirected_network, 1, 3)
    print(path) # Prints 1 2 3

    set_weight(my_undirected_network, 1, 2, 999)

    path = shortest_path(my_undirected_network, 1, 3)
    print(path) # Prints 1 6 5 4 3
}

See Also