-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnearest_neighbor.cpp
47 lines (40 loc) · 1.1 KB
/
nearest_neighbor.cpp
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
#include "graph_template.h"
struct NearestNeighbor : Tour
{
int find_nearest(int current_vertex)
{
visit(current_vertex);
ld shortest_dist = INF;
int next_vertex = -1;
for (int i = 0; i < n; i++)
{
if (!check_vis(i) && adj_matrix[current_vertex][i] < shortest_dist)
{
shortest_dist = adj_matrix[current_vertex][i];
next_vertex = i;
}
}
return next_vertex;
}
NearestNeighbor (vector<pld> cities, function<ld(pld, pld)> temp_dist, int start_vertex) : Tour(cities, temp_dist)
{
int current_vertex = start_vertex;
while (current_vertex != -1)
{
path.push_back(current_vertex);
current_vertex = find_nearest(current_vertex);
}
}
};
int main()
{
init("city_list.txt");
vector<Tour> tours;
for (int i = 0; i < COORDINATE_LIST.size(); i++)
{
tours.push_back(NearestNeighbor(COORDINATE_LIST, earth_dist, i));
}
sort(tours.begin(),tours.end());
tours[0].print_path();
return 0;
}