Skip to content

Commit f36bf7b

Browse files
author
Jonathan Sharman
committed
Add DijkstraResults::path
1 parent 0abce9d commit f36bf7b

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/graph.rs

+21
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ impl<T: Node> DijkstraResults<T> {
7171
}
7272

7373
/// A digraph from `end` back through all shortest paths to the start node.
74+
/// If `end` is not reachable from the start node, then the start node will
75+
/// not be reachable from the returned digraph.
7476
pub fn backtrace(&self, end: T) -> Digraph<T> {
7577
let mut digraph = Digraph::new();
7678
let mut queue = vec![end];
@@ -85,6 +87,25 @@ impl<T: Node> DijkstraResults<T> {
8587
}
8688
digraph
8789
}
90+
91+
/// An arbitrary shortest path from the start node to `end`, if there is
92+
/// one.
93+
pub fn path(&self, end: T) -> Option<Vec<T>> {
94+
self.distances.contains_key(&end).then(|| {
95+
let mut node = end.clone();
96+
let mut path = vec![node.clone()];
97+
while let Some(parent) = self
98+
.parents
99+
.get(&node)
100+
.and_then(|parents| parents.iter().next())
101+
{
102+
node = parent.clone();
103+
path.push(node.clone());
104+
}
105+
path.reverse();
106+
path
107+
})
108+
}
88109
}
89110

90111
impl<T: Node> Digraph<T> {

0 commit comments

Comments
 (0)