你如何使用 Rust 的 petgraph 执行过滤搜索?

How do you perform a filtered search with Rust's petgraph?

Rust 的 Petgraph 库有一堆 filter 'adaptors', but I haven't been able to find any examples or tutorials for how to use them. Some (but not all) have constructors, such as EdgeFiltered.from_fn() which takes a graph and a function, but it's not clear how you'd then use it with the search methods like Dfs or astar 因为它们没有过滤器参数。

那么如何使用这些过滤器?例如,如果我有一个具有整数边权重的图,你会如何:

  1. 执行深度优先搜索但排除权重为负的边,
  2. 执行排除负权重边的 astar 搜索?

适配器实现 GraphBase,您只需将图形包装在其中并将适配器结构传递给例如Dfs:

use petgraph::Graph;
use petgraph::visit::Dfs;
use petgraph::visit::EdgeFiltered;

fn main() {
    let mut graph = Graph::<(), i64>::new();
    let a = graph.add_node(());
    let b = graph.add_node(());
    let e = graph.add_edge(a, b, -1);
    let filtered = EdgeFiltered::from_fn(&graph, |edge_ref| *edge_ref.weight() > 0 );
    let dfs = Dfs::new(&filtered, a);
}

Playground Link