-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.rs
35 lines (31 loc) · 876 Bytes
/
dijkstra.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::cmp::Reverse;
use std::collections::BinaryHeap;
const INF_DIST: usize = std::usize::MAX;
type Graph = Vec<Vec<(usize, usize, usize)>>;
/// Dijkstra's algorithm
#[allow(clippy::ptr_arg)]
pub fn dijkstra(g: &Graph, start: usize) -> Vec<usize> {
let n = g.len();
let mut vis = vec![false; n];
let mut dist = vec![INF_DIST; n];
let mut heap = BinaryHeap::new();
dist[start] = 0;
heap.push(Reverse((0, start)));
while let Some(Reverse((cost, v))) = heap.pop() {
if dist[v] < cost {
continue;
}
vis[v] = true;
for e in &g[v] {
let (_, d, w) = &e;
if vis[*d] {
continue;
}
if dist[*d] > dist[v] + w {
dist[*d] = dist[v] + w;
heap.push(Reverse((dist[*d], *d)));
}
}
}
dist
}