Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

After working on my program some more, i've encountered a logic error where the ouput should be No Hamiltonian Cycle exists but im getting

After working on my program some more, i've encountered a logic error where the ouput should be "No Hamiltonian Cycle exists" but im getting 1. How do i change my code to account for if no hamiltonian cycle exists?
Here is the code:
double TSP(const std::vector& edges, unsigned int n_vertices){
/* IMPLEMENT THIS FUNCTION */
double min_cost = std::numeric_limits::infinity();
// Iterate through all permutations of vertices
std::vector permutation(n_vertices);
for (vertex_t i =0; i < n_vertices; ++i)
permutation[i]= i;
do {
double cost =0.0;
// Calculate the cost of the current permutation
for (size_t i =0; i < n_vertices; ++i){
vertex_t src = permutation[i];
vertex_t dst = permutation[(i +1)% n_vertices];
// Find the corresponding edge and add its weight to the total cost
for (const auto& edge : edges){
if (std::get<0>(edge)== src && std::get<1>(edge)== dst){
cost += std::get<2>(edge);
break;
}
}
}
// Update the minimum cost if the current permutation has lower cost
if (cost < min_cost)
min_cost = cost;
} while (std::next_permutation(permutation.begin(), permutation.end()));
return min_cost;
}
For more context, this is the Traveling Salesman Problem. I think it would be a simple if statement, but I don't know what to check.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

PostgreSQL Up And Running A Practical Guide To The Advanced Open Source Database

Authors: Regina Obe, Leo Hsu

3rd Edition

1491963417, 978-1491963418

More Books

Students also viewed these Databases questions