Skip to main content

k_shortest_paths

Function k_shortest_paths 

Source
pub fn k_shortest_paths(
    graph: &Graph,
    source: VertexId,
    target: VertexId,
    weights: &[f64],
    k: usize,
    mode: DijkstraMode,
) -> IgraphResult<Vec<KShortestPath>>
Expand description

Finds the k shortest loopless paths between source and target.

Returns up to k paths in order of increasing total weight. If fewer than k paths exist, fewer are returned.

weights must have length ecount() and contain non-negative values. Edges with weight f64::INFINITY are treated as absent.

§Errors

  • VertexOutOfRange if source or target exceeds vcount().
  • InvalidArgument if weights length differs from ecount().
  • InvalidArgument if weights contains negative values.

§Examples

use rust_igraph::{Graph, k_shortest_paths, DijkstraMode};

// Diamond: 0→1→3, 0→2→3 (two simple paths of equal length)
let mut g = Graph::with_vertices(4);
g.add_edge(0, 1).unwrap(); // edge 0
g.add_edge(1, 3).unwrap(); // edge 1
g.add_edge(0, 2).unwrap(); // edge 2
g.add_edge(2, 3).unwrap(); // edge 3
let w = vec![1.0; 4];
let paths = k_shortest_paths(&g, 0, 3, &w, 3, DijkstraMode::All).unwrap();
assert_eq!(paths.len(), 2); // only 2 simple paths exist
assert!((paths[0].weight - 2.0).abs() < 1e-12);
assert!((paths[1].weight - 2.0).abs() < 1e-12);