Skip to main content

greedy_routing

Function greedy_routing 

Source
pub fn greedy_routing<G, F, K>(
    graph: G,
    source: G::NodeId,
    destination: G::NodeId,
    distance: F,
) -> Result<(Vec<G::NodeId>, K), NodeNotReachedError>
where G: IntoEdges + NodeCount + NodeIndexable + Visitable, G::NodeId: Eq + Hash, F: Fn(G::NodeId, G::NodeId) -> K, K: Measure + Copy,
Expand description

Greedy routing shortest path algorithm.

Successively follows the neighbor closest to destination from source until destination is reached. The closest neighbor is the node that minimizes the distance function.

Returns the greedy path and the sum of the distances in the path. A NodeNotReachedError is returned if the greedy routing fails to reach destination.

ยงExample:


use rustworkx_core::petgraph;
use rustworkx_core::geometry::{euclidean_distance, greedy_routing};

let g = petgraph::graph::UnGraph::<i32, ()>::from_edges(&[
    (0, 1), (1, 2), (2, 3), (1, 4), (4, 5), (2, 5), (5, 6)
]);

fn distance2d<G>(graph: &G, positions: &Vec<[f64; 2]>, u: G::NodeId, v: G::NodeId) -> f64 where G: petgraph::visit::NodeIndexable {
    euclidean_distance(&positions[graph.to_index(u)], &positions[graph.to_index(v)]).unwrap()
}

let positions = vec![[0., 0.], [1., 0.] , [2., 0.], [2.5, 0.], [1., 1.], [2., 1.], [3., 1.]];
let (path, dist) = greedy_routing(&g, 0.into(), 6.into(), |u, v| {distance2d(&g, &positions, u, v)}).unwrap();
assert_eq!(path, vec![0.into(), 1.into(), 2.into(), 5.into(), 6.into()]);
assert!( (dist - (1.+1.+1.+1.)).abs() < 1e-15 );