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

我有一个方向图,想要找到从节点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的实现),并且与前一个版本取消注释,并返回前一个版本,那么最终版本将更快,因为答案将类似于前任[前任[d]].

最佳答案 作为 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)]
点赞