TSP UpdatedVersion
TSP UpdatedVersion
h>
#include <limits.h>
#define MAX 16 // Maximum number of cities
#define INF INT_MAX // Infinity (used for no direct connection)
// Function to calculate the minimum cost using Dynamic Programming and Bitmasking
int tsp(int graph[MAX][MAX], int mask, int pos, int V)
{
// If all cities have been visited, return the cost to go back to the start (city 0)
if (mask == (1 << V) - 1) {
return (graph[pos][0] != INF) ? graph[pos][0] : INF; // Return INF if no direct route
}
// If this path is better, update the minimum cost and the parent city
if (newCost < minCost) {
minCost = newCost;
parent[mask][pos] = city;
}
}
}
int main() {
int V;
int graph[MAX][MAX];
return 0;
}
Output
Enter the number of cities: 5
Enter the distances between the cities in matrix form (enter -1 for no direct route):
Distance from city 1 to city 1: 0
Distance from city 1 to city 2: 2
Distance from city 1 to city 3: 4
Distance from city 1 to city 4: 6
Distance from city 1 to city 5: -1
Distance from city 2 to city 1: 2
Distance from city 2 to city 2: 0
Distance from city 2 to city 3: -1
Distance from city 2 to city 4: 7
Distance from city 2 to city 5: 2
Distance from city 3 to city 1: 4
Distance from city 3 to city 2: -1
Distance from city 3 to city 3: 0
Distance from city 3 to city 4: 1
Distance from city 3 to city 5: 4
Distance from city 4 to city 1: 6
Distance from city 4 to city 2: 7
Distance from city 4 to city 3: 1
Distance from city 4 to city 4: 0
Distance from city 4 to city 5: 1
Distance from city 5 to city 1: -1
Distance from city 5 to city 2: 2
Distance from city 5 to city 3: 4
Distance from city 5 to city 4: 1
Distance from city 5 to city 5: 0
The minimum cost of the TSP is: 10
The path taken is: 1 -> 2 -> 5 -> 4 -> 3 -> 1