Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

(Using C++) Examine the following image (GeeksforGeeks, n.d.): Solve the traveling salesman problem (TSP) based on the given image using dynamic programming. The TSP ensures

(Using C++)

Examine the following image (GeeksforGeeks, n.d.):

Solve the traveling salesman problem (TSP) based on the given image using dynamic programming. The TSP ensures that every node is visited exactly once with the minimum weight.

Solve this problem using the following steps:

  1. Implement a graph with all of the vertices and weights.
  2. Create a node structure; each node should have the same value based on to the above.
  3. Use dynamic programming to solve the TSP.
  4. Print all of the node values based on the output from dynamic programming.

Sol79:

#include

using namespace std;

const int N = 4;

const int VISITED_ALL = (1)>

int tsp[N][1

int dist[N][N] = {{0, 10, 15, 20},

{10, 0, 35, 25},

{15, 35, 0, 30},

{20, 25, 30, 0}};

int tsp_dp(int mask, int pos){

if(mask == VISITED_ALL){

return dist[pos][0];

}

if(tsp[pos][mask] != -1){

return tsp[pos][mask];

}

int ans = INT_MAX;

for(int city = 0; city

if((mask&(1))>

int newAns = dist[pos][city] + tsp_dp((mask|(1)),>

ans = min(ans, newAns);

}

}

tsp[pos][mask] = ans;

return ans;

}

int main(){

memset(tsp, -1, sizeof(tsp));

cout(1,>

return 0;

}

In this code, we first define the number of vertices as N and the maximum value of the visited nodes as VISITED_ALL. Then we define the distance matrix dist[N][N], which stores the weight between each pair of nodes.

The tsp_dp function takes two arguments, mask and pos. Mask is an integer that keeps track of the visited nodes, and pos is the current node. If all the nodes are visited, the function returns the distance between the current node and the starting node. If the solution for the current node and mask is already calculated, we return the previously calculated value.

We then iterate through all the unvisited nodes and call the tsp_dp function recursively for each unvisited node. We calculate the distance for each path, and the minimum distance is stored in the tsp array.

Finally, we call the tsp_dp function with the starting node and a mask value of 1 (as the starting node is already visited), and the function returns the minimum distance. We print the minimum distance as output.

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

Mobile Usability

Authors: Jakob Nielsen, Raluca Budiu

1st Edition

0133122131, 9780133122138

More Books

Students also viewed these Programming questions