TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
travelling_salesman_problem.cpp
Go to the documentation of this file.
1
20#include <algorithm>
21#include <cassert>
22#include <cstdint>
23#include <iostream>
24#include <limits>
25#include <vector>
26
31namespace graph {
41int TravellingSalesmanProblem(std::vector<std::vector<uint32_t>> *cities,
42 int32_t src, uint32_t V) {
44 std::vector<uint32_t> vtx;
45 for (uint32_t i = 0; i < V; i++) {
46 if (i != src) {
47 vtx.push_back(i);
48 }
49 }
50
52 int32_t min_path = 2147483647;
53 do {
55 int32_t curr_weight = 0;
56
58 int k = src;
59 for (int i : vtx) {
60 curr_weight += (*cities)[k][i];
61 k = i;
62 }
63 curr_weight += (*cities)[k][src];
64
66 min_path = std::min(min_path, curr_weight);
67
68 } while (next_permutation(vtx.begin(), vtx.end()));
69
70 return min_path;
71}
72} // namespace graph
73
78static void tests() {
79 std::cout << "Initiatinig Predefined Tests..." << std::endl;
80 std::cout << "Initiating Test 1..." << std::endl;
81 std::vector<std::vector<uint32_t>> cities = {
82 {0, 20, 42, 35}, {20, 0, 30, 34}, {42, 30, 0, 12}, {35, 34, 12, 0}};
83 uint32_t V = cities.size();
84 assert(graph::TravellingSalesmanProblem(&cities, 0, V) == 97);
85 std::cout << "1st test passed..." << std::endl;
86
87 std::cout << "Initiating Test 2..." << std::endl;
88 cities = {{0, 5, 10, 15}, {5, 0, 20, 30}, {10, 20, 0, 35}, {15, 30, 35, 0}};
89 V = cities.size();
90 assert(graph::TravellingSalesmanProblem(&cities, 0, V) == 75);
91 std::cout << "2nd test passed..." << std::endl;
92
93 std::cout << "Initiating Test 3..." << std::endl;
94 cities = {
95 {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0}};
96 V = cities.size();
97 assert(graph::TravellingSalesmanProblem(&cities, 0, V) == 80);
98 std::cout << "3rd test passed..." << std::endl;
99}
100
105int main() {
106 tests(); // run self-test implementations
107 std::vector<std::vector<uint32_t>> cities = {
108 {0, 5, 10, 15}, {5, 0, 20, 30}, {10, 20, 0, 35}, {15, 30, 35, 0}};
109 uint32_t V = cities.size();
110 std::cout << graph::TravellingSalesmanProblem(&cities, 0, V) << std::endl;
111 return 0;
112}
Graph Algorithms.
int TravellingSalesmanProblem(std::vector< std::vector< uint32_t > > *cities, int32_t src, uint32_t V)
Function calculates the minimum path distance that will cover all the cities starting from the source...
static void tests()
Self-test implementations.
int main()
Main function.