pub struct SimpleGraph<W> { /* private fields */ }Expand description
A simple and undirected graph.
A simple graph assumes that the node indexing starts from 0 and is not equipped with a hash map
for a mapping from external complex objects to internal graph indices. As a result, SimpleGraph
doesn’t have no runtime overhead for such object storage and mapping.
§Examples
The following example shows how to construct a graph and find the shortest path between node 1 and 5. The data is taken from the illustration in Wikipedia’s page for Dijkstra’s algorithm.
Here, the numbering is adjusted so that the node indexing starts from 0.
use pheap::graph::SimpleGraph;
let mut g = SimpleGraph::<u32>::with_capacity(6);
g.add_weighted_edges(0, 1, 7);
g.add_weighted_edges(0, 2, 9);
g.add_weighted_edges(0, 5, 14);
g.add_weighted_edges(1, 2, 10);
g.add_weighted_edges(1, 3, 15);
g.add_weighted_edges(2, 5, 2);
g.add_weighted_edges(2, 3, 11);
g.add_weighted_edges(3, 4, 6);
g.add_weighted_edges(4, 5, 9);
// Finds an SSSP from 0 to 4.
let mut sp = g.sssp_dijkstra(0, &[4]);
assert_eq!(1, sp.len());
let sp = sp.pop().unwrap();
assert_eq!(20, sp.dist());
assert_eq!(&[0, 2, 5, 4], sp.path().as_slice());
// Adds a disconnected component to the graph.
g.add_weighted_edges(6, 7, 2);
g.add_weighted_edges(6, 8, 3);
// Finds an SSSP starting from 0. The result can be used for later query.
let lsp = g.sssp_dijkstra_lazy(0);
let lsp = g.sssp_dijkstra_lazy(0);
let sp = lsp.get(7);
assert_eq!(false, sp.is_feasible());
let sp = lsp.get(4);
assert_eq!(true, sp.is_feasible());
assert_eq!(20, sp.dist());
assert_eq!(&[0, 2, 5, 4], sp.path().as_slice());
Implementations§
Source§impl<W> SimpleGraph<W>
impl<W> SimpleGraph<W>
Sourcepub fn with_capacity(n_nodes: usize) -> Self
pub fn with_capacity(n_nodes: usize) -> Self
Creates an empty graph with the given capacitiy of nodes.
Sourcepub fn add_weighted_edges(&mut self, node1: usize, node2: usize, weight: W)
pub fn add_weighted_edges(&mut self, node1: usize, node2: usize, weight: W)
Adds a weighted edge to the graph.
If the edge already exists in the graph, the weight will be updated.
Sourcepub fn sssp_dijkstra(&self, src: usize, dest: &[usize]) -> Vec<ShortestPath<W>>
pub fn sssp_dijkstra(&self, src: usize, dest: &[usize]) -> Vec<ShortestPath<W>>
Finds the shortest paths from a source node to destination nodes.
If you want to keep the result for later usage and/or want to save memory, consider using
the lazy version SimpleGraph::sssp_dijkstra_lazy, which returns the intermediate result
from Dijkstra’s algorithm.
Sourcepub fn sssp_dijkstra_lazy(&self, src: usize) -> LazyShortestPaths<W>
pub fn sssp_dijkstra_lazy(&self, src: usize) -> LazyShortestPaths<W>
Finds the shortest paths from a source node to all nodes and returns the intermediate result for later usage.