-
Notifications
You must be signed in to change notification settings - Fork 0
/
TSP.c
52 lines (51 loc) · 953 Bytes
/
TSP.c
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
#include <stdio.h>
#include <stdlib.h>
int n, distance[10][10], visited[10], total_cost=0;
int find_minimum(int c)
{
int i, nc=99;
int min=99,kmin;
for(i=0;i < n;i++)
{
if((distance[c][i]!=0)&&(visited[i]==0))
if(distance[c][i]+distance[i][c] < min)
{
min=distance[i][0]+distance[c][i];
kmin=distance[c][i];
nc=i;
}
}
if(min != 99)
total_cost += kmin;
return nc;
}
void tsp(int city)
{
int i,ncity;
visited[city] = 1;
printf("%d >> ",city + 1);
ncity = find_minimum(city);
if(ncity == 99)
{
ncity = 0;
printf("%d", ncity+1);
total_cost += distance[city][ncity];
return;
}
tsp(ncity);
}
void main(){
printf("Enter number of vertices:: ");
scanf("%d", &n);
printf("\nEnter distance matrix:: \n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d", &distance[i][j]);
}
visited[i]=0;
}
printf("\nShortest path traced: \n");
tsp(0);
printf("\n\nMinimum total_cost:");
printf("%d",total_cost);
}