1. Permutation Backtracking
Intuition
Fix the starting city at 0. Generate all (N - 1)! permutations of the remaining cities 1 \dots N - 1. For each permutation, calculate the cost of traversing the sequence and returning to city 0. Find the minimum cost among all permutations.
Algorithm
- Initialize
minCost = infinity. - Create an array of cities
[1, 2, ..., n - 1]. - Generate all permutations of these cities.
- For each permutation
[c1, c2, ..., cn-1]: -
total = cost[0][c1] + cost[c1][c2] + ... + cost[cn-1][0] -
minCost = min(minCost, total) - Return
minCost.
#include <iostream>#include <vector>#include <numeric>#include <algorithm>#include <climits> int tspBrute(int n, const std::vector<std::vector<int>>& cost) { std::vector<int> cities; for (int i = 1; i < n; ++i) cities.push_back(i); int minCost = INT_MAX; do { int currentCost = cost[0][cities[0]]; for (int i = 0; i < (int)cities.size() - 1; ++i) { currentCost += cost[cities[i]][cities[i + 1]]; } currentCost += cost[cities.back()][0]; minCost = std::min(minCost, currentCost); } while (std::next_permutation(cities.begin(), cities.end())); return minCost;} int main() { int n = 3; std::vector<std::vector<int>> cost = {{0, 10, 15}, {10, 0, 20}, {15, 20, 0}}; std::cout << "TSP (Brute Force): " << tspBrute(n, cost) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N!) because there are (N - 1)! permutations, each evaluated in O(N) time. - Space complexity:
O(N) for recursion stack and permutation storage.