Graphs in Rust with petgraph
Choosing graph storage and algorithms in Rust
petgraph 0.8.3 is a Rust library for graph data structures and algorithms, and Graphviz import/export. Its nodes and edges can hold arbitrary associated data, which the API calls weights. Edges can be directed or undirected.
The usual starting point is Graph, an adjacency-list collection with O(|V| + |E|) space. It identifies nodes and edges with compact indices, so removing an item can move the last item into its slot and invalidate an index. StableGraph keeps indices stable across removals, trading some memory and API coverage for that property.
The other graph types suit different identities or layouts:
GraphMapuses copyable, hashable node values as keys, has constant-time edge existence checks, and does not allow parallel edges.MatrixGraphstores an adjacency matrix and fits dense graphs.Csrstores a sparse adjacency matrix and is useful when the graph is built once and queried many times.
The algo module includes Dijkstra, A*, Bellman–Ford, topological sorting, strongly connected components, minimum spanning trees, maximum flow, graph isomorphism, and more. visit provides reusable depth-first and breadth-first traversals. These algorithms can supply several stages of [[layer-graph-drawing|a layered graph drawing]], but petgraph does not provide the complete layout pipeline.
use petgraph::algo::dijkstra;
use petgraph::graph::UnGraph;
let graph = UnGraph::<(), ()>::from_edges(&[(0, 1), (1, 2), (2, 3)]);
let distances = dijkstra(&graph, 0.into(), Some(3.into()), |_| 1);
assert_eq!(distances[&3.into()], 3);Did you enjoy this article?
Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.