dijkstra

Function dijkstra 

Source
pub fn dijkstra<G>(
    graph: &G,
    source: NodeId,
) -> Result<DijkstraResult, GraphError>
where G: Graph<Weight = f64>,
Expand description

Runs Dijkstra’s algorithm from source and returns shortest distances and the parent map.

Requires all edge weights to be non-negative. Negative weights will produce incorrect results without error (use bellman_ford instead).

Uses a binary min-heap (BinaryHeap<Reverse<…>>) with lazy deletion: stale (distance, node) entries are skipped rather than updated in place.

§Errors

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

§Complexity

O((V + E) log V) with a binary heap.

§Examples

use graph_core::{AdjacencyList, Graph};
use graph_shortest_path::dijkstra;

let mut g: AdjacencyList<()> = AdjacencyList::directed();
let a = g.add_node(());
let b = g.add_node(());
let c = g.add_node(());
g.add_edge(a, b, 1.0).unwrap();
g.add_edge(b, c, 2.0).unwrap();
g.add_edge(a, c, 10.0).unwrap();

let result = dijkstra(&g, a).unwrap();
assert_eq!(result.distances[&c], 3.0); // a→b→c is cheaper than a→c
assert_eq!(result.parents[&c], b);