|
66 | 66 | //! // to each node. This implementation isn't memory-efficient as it may leave duplicate
|
67 | 67 | //! // nodes in the queue. It also uses `usize::MAX` as a sentinel value,
|
68 | 68 | //! // for a simpler implementation.
|
69 |
| -//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> usize { |
| 69 | +//! fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> { |
70 | 70 | //! // dist[node] = current shortest distance from `start` to `node`
|
71 | 71 | //! let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();
|
72 | 72 | //!
|
|
79 | 79 | //! // Examine the frontier with lower cost nodes first (min-heap)
|
80 | 80 | //! while let Some(State { cost, position }) = heap.pop() {
|
81 | 81 | //! // Alternatively we could have continued to find all shortest paths
|
82 |
| -//! if position == goal { return cost; } |
| 82 | +//! if position == goal { return Some(cost); } |
83 | 83 | //!
|
84 | 84 | //! // Important as we may have already found a better way
|
85 | 85 | //! if cost > dist[position] { continue; }
|
|
99 | 99 | //! }
|
100 | 100 | //!
|
101 | 101 | //! // Goal not reachable
|
102 |
| -//! usize::MAX |
| 102 | +//! None |
103 | 103 | //! }
|
104 | 104 | //!
|
105 | 105 | //! fn main() {
|
|
140 | 140 | //! // Node 4
|
141 | 141 | //! vec![]];
|
142 | 142 | //!
|
143 |
| -//! assert_eq!(shortest_path(&graph, 0, 1), 1); |
144 |
| -//! assert_eq!(shortest_path(&graph, 0, 3), 3); |
145 |
| -//! assert_eq!(shortest_path(&graph, 3, 0), 7); |
146 |
| -//! assert_eq!(shortest_path(&graph, 0, 4), 5); |
147 |
| -//! assert_eq!(shortest_path(&graph, 4, 0), usize::MAX); |
| 143 | +//! assert_eq!(shortest_path(&graph, 0, 1), Some(1)); |
| 144 | +//! assert_eq!(shortest_path(&graph, 0, 3), Some(3)); |
| 145 | +//! assert_eq!(shortest_path(&graph, 3, 0), Some(7)); |
| 146 | +//! assert_eq!(shortest_path(&graph, 0, 4), Some(5)); |
| 147 | +//! assert_eq!(shortest_path(&graph, 4, 0), None); |
148 | 148 | //! }
|
149 | 149 | //! ```
|
150 | 150 |
|
|
0 commit comments