Skip to main content

dijkstra_attributed

Function dijkstra_attributed 

Source
pub fn dijkstra_attributed<N, E, F>(
    graph: &AttributedGraph<N, E>,
    source: NodeId,
    cost_fn: F,
) -> Result<HashMap<NodeId, f64>>
where F: Fn(&E) -> f64,
Expand description

Generalised Dijkstra shortest-path algorithm on an attributed graph.

cost_fn is called for each edge and must return a non-negative f64 cost. Negative costs will produce incorrect results (no check is performed for performance reasons).

Returns a map from each reachable NodeId to its minimum total cost from source. Unreachable nodes are absent from the map.

§Errors

Returns GraphError::NodeNotFound if source is not in the graph.

§Example

use scirs2_graph::attributed_graph::{AttributedGraph, dijkstra_attributed, NodeId};

let mut g = AttributedGraph::<(), f64>::new();
let a = g.add_node(());
let b = g.add_node(());
let c = g.add_node(());
g.add_edge(a, b, 2.0).unwrap();
g.add_edge(b, c, 3.0).unwrap();
g.add_edge(a, c, 10.0).unwrap();

let dist = dijkstra_attributed(&g, a, |e| *e).unwrap();
assert_eq!(dist[&b], 2.0);
assert_eq!(dist[&c], 5.0); // 2 + 3, not 10