Thanks to visit codestin.com
Credit goes to docs.rs

Function dijkstra

Source
pub fn dijkstra<T: Display + Clone + Eq + Hash>(
    graph: &mut Graph<T>,
    source_node_id: &T,
) -> Result<ShortestPathTree<T>, RunAlgorithmError>
Expand description

Calculates the shortest distance between one source node and all other nodes on the graph using Dijkstra’s algorithm.

Dijkstra’s algorithm does not work properly on graphs with negative edge weights. Use bellman_ford instead if your graph contains those edges with negative weights.

This function takes a graph on which the algorithm should be run and the id of the start node.

Returns Ok(ShortestPathTree) when the algorithm was run on the graph or Err(()) when the start node is missing from the graph.

Once the algorithm was run successfully, the resulting ShortestPathTree can be used to receive the shortest distance and path to a node.

§Example

use simple_graph_algorithms::{Graph, ShortestPathTree, algorithms::{dijkstra, RunAlgorithmError}};
 
// Create new graph
let mut graph: Graph<char> = Graph::new();
 
// Add nodes to graph
graph.add_node('a');
graph.add_node('b');
graph.add_node('c');
graph.add_node('d');
 
// Add edges between nodes
graph.add_edge(3, &'a', &'b');
graph.add_edge(4, &'a', &'c');
graph.add_edge(5, &'b', &'a');
graph.add_edge(9, &'c', &'a');
graph.add_edge(4, &'c', &'d');
 
/// Run Dijkstra's algorithm to calculate the shortest path tree, starting at node a.
let spt = dijkstra(&mut graph, &'a')?;
 
// Retrieve shortest distances
assert_eq!(spt.shortest_distance(&'c'), Some(4));
assert_eq!(spt.shortest_distance(&'d'), Some(8));
 
/// When run on a graph, that is missing the start node an Err is returned:
assert_eq!(dijkstra(&mut graph, &'e'), Err(RunAlgorithmError::SourceNodeMissing));