petgraph的哪种算法会找到从A到B的最短路径?

时间:2017-04-14 23:44:33

标签: rust

我有一个方向图,想要找到从节点A到节点B的最短路径。我在crates.io上搜索并找到了petgraph,它看起来像是最受欢迎的箱子。它implements a number of algorithms,但没有一个能解决我的任务。我错过了什么吗?

例如,Dijkstra's algorithm返回路径成本,但哪条路径的成本最低? Bellman-Ford algorithm返回路径成本 和节点,但没有路径。

这是我从图表中打印路径的最简单方法:

extern crate petgraph;
use petgraph::prelude::*;
use petgraph::algo::dijkstra;

fn main() {
    let mut graph = Graph::<&str, i32>::new();
    let a = graph.add_node("a");
    let b = graph.add_node("b");
    let c = graph.add_node("c");
    let d = graph.add_node("d");

    graph.extend_with_edges(&[(a, b, 1), (b, c, 1), (c, d, 1), (a, b, 1), (b, d, 1)]);
    let paths_cost = dijkstra(&graph, a, Some(d), |e| *e.weight());
    println!("dijkstra {:?}", paths_cost);

    let mut path = vec![d.index()];
    let mut cur_node = d;

    while cur_node != a {
        let m = graph
            .edges_directed(cur_node, Direction::Incoming)
            .map(|edge| paths_cost.get(&edge.source()).unwrap())
            .min()
            .unwrap();
        let v = *m as usize;
        path.push(v);
        cur_node = NodeIndex::new(v);
    }

    for i in path.iter().rev().map(|v| graph[NodeIndex::new(*v)]) {
        println!("path: {}", i);
    }
}

据我所知,我需要根据结果自己计算路径 dijkstra

我相信如果我自己实施dijkstra(基于dijkstra.rs执行我的实施),并使用predecessor取消注释,并返回predecessor,那么最后的变体将更快,因为答案将类似于predecessor[predecessor[d]]

1 个答案:

答案 0 :(得分:2)

作为mentioned in the comments(由图书馆的主要作者,不少),您可以使用A *(astar)算法:

extern crate petgraph;

use petgraph::prelude::*;
use petgraph::algo;

fn main() {
    let mut graph = Graph::new();

    let a = graph.add_node("a");
    let b = graph.add_node("b");
    let c = graph.add_node("c");
    let d = graph.add_node("d");

    graph.extend_with_edges(&[(a, b, 1), (b, c, 1), (c, d, 1), (a, b, 1), (b, d, 1)]);

    let path = algo::astar(
        &graph,
        a,               // start
        |n| n == d,      // is_goal
        |e| *e.weight(), // edge_cost
        |_| 0,           // estimate_cost
    );

    match path {
        Some((cost, path)) => {
            println!("The total cost was {}: {:?}", cost, path);
        }
        None => println!("There was no path"),
    }
}
The total cost was 2: [NodeIndex(0), NodeIndex(1), NodeIndex(3)]