forked from dscgecbsp/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTravellingSalesmanProblem.cpp
75 lines (60 loc) · 1.26 KB
/
TravellingSalesmanProblem.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Travelling Salesman Problem (TSP): Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible route that visits every city exactly once and returns to the starting point.
# include <stdio.h>
int nodes[4]={0,0,0,0};
int values[4][4]={{0,16,11,6},{8,0,13,16},{4,7,0,9},{5,12,2,0}};
int cost=0;
int tsp(int);
void min_cost(int);
void min_cost(int city)
{
int nearest;
nodes[city]=1;
printf("%d ",city+1);
nearest=tsp(city);
if(nearest==999)
{
nearest=0;
printf("%d ",nearest+1);
cost+=values[city][nearest];
return;
}
min_cost(nearest);
}
int tsp(int c)
{
int nearest=999;
int min=999,temp;
for(int count=0;count<4;count++)
{
if((values[c][count]!=0) && (nodes[count]==0))
{
if(values[c][count]<min)
{
min=values[count][0]+values[c][count];
}
temp=values[c][count];
nearest=count;
}
}
if(min!=999)
{
cost+=temp;
}
return nearest;
}
int main()
{
printf("Travelling Salesman Problem (Greedy Algorithm)\n\n");
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
printf("%d ",values[i][j]);
}
printf("\n");
}
printf("\n\nPath: ");
min_cost(0);
printf("\nCost: %d",cost);
return 0;
}