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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use crate::algo::graph::WeightedAdjacencyMatrix;
use crate::algo::misc::permutations::*;
pub fn tsp(g: &WeightedAdjacencyMatrix, start: usize) -> (f64, Vec<usize>) {
let n = g.node_count();
let permutations = (0..n)
.filter(|&i| i != start)
.collect::<Vec<_>>()
.permutations();
let mut tour = vec![];
let mut best_tour_cost = f64::INFINITY;
for perm in permutations {
let perm = unsafe { &*perm };
let cost = compute_tour_cost(g, perm, start);
if cost < best_tour_cost {
best_tour_cost = cost;
tour = perm.to_owned();
}
}
tour.insert(0, start);
(best_tour_cost, tour)
}
fn compute_tour_cost(g: &WeightedAdjacencyMatrix, tour: &[usize], start: usize) -> f64 {
tour.windows(2)
.fold(0., |cost, step| cost + g[step[0]][step[1]])
+ g[start][*tour.first().unwrap()]
+ g[*tour.last().unwrap()][start]
}