Javatpoint Logo
Javatpoint Logo

Travelling Salesman Problem

In the following tutorial, we will discuss the Travelling Salesman Problem with its solution and implementation in different programming languages using different approaches.

So, let's get started.

Understanding the Travelling Salesman Problem

The Travelling Salesman Problem (also known as the Travelling Salesperson Problem or TSP) is an NP-hard graph computational problem where the salesman must visit all cities (denoted using vertices in a graph) given in a set just once. The distances (denoted using edges in the graph) between all these cities are known. We are requested to find the shortest possible route in which the salesman visits all the cities and returns to the origin city.

Note:

There is a difference between Hamiltonian Cycle and TSP. The Hamiltonian Cycle problem is the problem where we have to find if there exists a tour that visits every city accurately once. However, in this problem, we already know that Hamiltonian Tour exists as the graph is complete, and in fact, there exist many such tours. Therefore, the problem is to find a minimum weight Hamiltonian Cycle.

Let us consider the following examples demonstrating the problem:

Example 1 of Travelling Salesman Problem

Input:

Travelling Salesman Problem

Output:

Travelling Salesman Problem

Example 2 of Travelling Salesman Problem

Input:

Travelling Salesman Problem

Output:

Minimum Weight Hamiltonian Cycle: EACBDE = 32

Solution of the Travelling Salesman Problem

In the following section, we will discuss different approaches that we will use to solve the problem and their implementations in different programming languages like C, C++, Java, and Python.

The following are some approaches that we are going to use:

  1. Simple or Nave Approach
  2. Dynamic Programming Approach
  3. Greedy Approach

Let us now discuss the approaches mentioned above in detail:

Solving Travelling Salesman Problem using Simple Approach

In the following approach, we will solve the problem using the steps mentioned below:

Step 1: Firstly, we will consider City 1 as the starting and ending point. Since the route is cyclic, any point can be considered a starting point.

Step 2: As the second step, we will generate all the possible permutations of the cities, which are (n-1)!

Step 3: After that, we will find the cost of each permutation and keep a record of the minimum cost permutation.

Step 4: At last, we will return the permutation with minimum cost.

Implementation of Simple Approach to Solve Travelling Salesman Problem in Different Programming Languages

Now that we have successfully understood the steps for the simple approach to solve Travelling Salesman Problem, it is time to see its implementation in different programming languages like C++, Java, and Python.

Code Implementation in C++

The following is the implementation of the Travelling Salesman Problem's Algorithm in the C++ Programming Language:

File: TSP.cpp

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we have included the 'bits/stdc++.h' header file, used the standard namespace, and defined a constant value as V = 4 that represents the number of nodes in the graph. We have then defined the function to find the minimum weight Hamiltonian cycle cost as travelling_salesman_problem() that accepts a two-dimensional array representing the graph and an integer representing the starting node. Inside this function, we have created a vector in order to store the nodes from the graph. We have then iterated through the defined number of vertices using the for-loop and used the vector's push_back() method to push each element into the vector if it is not the source node. We have then set an initial value for minimum path weight as INT_MAX (maximum integer value). We then used the do-while loop to update the minimum path weight for all the possible permutations. Inside this loop, we have set an initial value of the current path weight as 0 and then iterated through the vector incrementing the current path weight according to the graph's edges. We have then updated the minimum path weight by comparing the current path weight and the stored value. We have then returned the resulting path weight and defined a main function. We have defined the graph inside the main function using the adjacency matrix and set a starting node. We have then called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost and stored the returned value in a variable. At last, we have printed this variable for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Java

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Java Programming Language:

File: TSP.java

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we have imported everything from the 'java.util' library and defined the main class as TSP to solve the Travelling Salesman Problem. In this class, we have initialized a constant value as V = 4, which represents the total number of nodes in the graph. We have then defined the method to find the minimum weight Hamiltonian cycle cost as travelling_salesman_problem() that accepts a two-dimensional array representing the graph and an integer representing the starting node. Inside this function, we have created an integer array using ArrayList to store the nodes from the graph. We have then iterated through the defined number of vertices using the for-loop and used the add() method to add each element into the vector if it is not the source node. We have then set an initial value for the minimum path weight as Integer.MAX_VALUE (maximum integer value). We then used the do-while loop to update the minimum path weight for all the possible permutations. Inside this loop, we have set an initial value of the current path weight as 0 and then iterated through the array incrementing the current path weight according to the graph's edges. We have then updated the minimum path weight by comparing the current path weight and the stored value. We have then returned the resulting path weight. After that, we have defined a few more methods that will help us swap the elements of the array, reverse them, and to do permutations. We then defined the main function, creating the graph using the adjacency matrix and setting a starting node. Then, we called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost and stored the returned value in a variable. At last, we have printed this variable for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Python

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Python Programming Language:

File: TSP.py

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we have imported the permutations class from the itertools module along with the maxsize variable from the sys module. We then initialized a constant value as V = 4, representing the total number of nodes in the graph. We have then defined the function to find the minimum weight Hamiltonian cycle cost as travelling_salesman_problem() that accepts a list representing the graph and an integer representing the starting node. Inside this function, we have created an empty list to store the nodes from the graph. We have then iterated through the defined number of vertices using the for-loop and used the append() method to add each element into the vector if it is not the source node. We have then set an initial value for the minimum path weight as maxsize (maximum integer value). We then instantiated the permutations() class for the number of nodes and used the for-loop to iterate through each permutation and update the minimum path weight accordingly. Inside this loop, we have set an initial value of the current path weight as 0 and then iterated through the list incrementing the current path weight according to the graph's edges. We have then updated the minimum path weight by comparing the current path weight and the stored value. We have then returned the resulting path weight. We then defined the main function, creating the graph and setting a starting node. Then, we called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost and stored the returned value in a variable. At last, we have printed this variable for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Time and Space Complexity of Travelling Salesman Problem Using Simple Approach

  • The Time Complexity of the Travelling Salesman Problem using the Simple or Nave Approach will be O(N!), where N is the number of cities.
  • The Space Complexity of the Travelling Salesman Problem using the Simple or Nave Approach will be O(1).

Solving Travelling Salesman Problem Using Dynamic Programming Approach

In the following approach, we will solve the problem using the steps mentioned below:

Step 1: In travelling salesman problem algorithm, we will accept a subset N of the cities that require to be visited, the distance among the cities, and starting city S as inputs. Each city is represented by a unique city id (let's say 1, 2, 3, 4, 5, ..., n).

Step 2: Let us consider 1 as the starting and ending point of the problem. For every other node V (except 1), we will calculate the minimum cost path having 1 as the starting point, V as the ending point, and all nodes appearing exactly once.

Step 3: Let the cost of this path cost (i), and the cost of the corresponding cycle would be cost(i) + distance(i, 1) where the distance(i, 1) from V to 1. Finally, we will return the minimum of all [cost(i) + distance(i, 1)] values.

The above procedure looks quite easy. However, the main question is how to calculate the cost(i)? In order to calculate the cost(i) with the help of Dynamic Programming, we are required to have some recursive relations in terms of sub-problems.

Let us define a term C(S, i) be the cost of the minimum cost path visiting each node in set S exactly once, beginning at 1 and ending at i. We will begin with all subsets of size 2 and calculate C(S, i) for all subsets S of size 3 and so on.

Note:

Node 1 must be present in every subset.

Implementation of Dynamic Programming Approach to Solve Travelling Salesman Problem in Different Programming Languages

We will now see the implementation of the Dynamic Programming solution using the Top-Down Recursive + Memorized approach in different programming languages like C++, Java, and Python.

To maintain the subsets, we can utilize the bitmasks in order to represent the remaining nodes in the subset. Since the operations are carried out faster using bits, and there are only a few nodes in the graph, bitmasks are better for usage.

For instance:

  • 10100 signifies that nodes 2 and 4 are left in set for processing.
  • 010010 signifies that nodes 1 and 4 are left in the subset.

Note:

Ignore the zeroth bit since the graph is 1-based.

Code Implementation in C++

The following is the implementation of the Travelling Salesman Problem's Algorithm in the C++ Programming Language:

File: TSP.cpp

Output:

Minimum Cost : 90

Explanation:

In the above code snippet, we included the iostream header file and used the standard namespace. We then defined a constant value to represent the total number of vertices, the maximum integer size to avoid overflow issues, a graph, and a matrix to perform memoization for the top-down recursion approach. We have then defined the function as travelling_salesman_problem() that accepts two parameters - the first parameter is iterable, and the second one is the bitmask. Inside this function, we have defined a base case for the recursion, which will execute only when the current and first bit is set in the mask, implying that all other nodes have already been visited. After that, we performed memorization and initialized the minimum cost as the maximum integer value. We then used the for-loop to iterate through all the nodes in the mask. We recursively calculated the cost of travelling the nodes in the mask except the selected one and then travelling back to starting node by taking the shortest possible path. For the main function, we have initialized the resultant cost as the maximum integer value and used the for-loop to iterate through the nodes of the graph and calculate the new minimum cost by calling the travelling_salesman_problem() function for that particular node and set the minimum cost value as the resultant cost. At last, we have printed the result for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Java

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Java Programming Language:

File: TSP.java

Output:

Minimum Cost : 90

Explanation:

In the above code snippet, we defined a class as TSP. Within this class, we defined a constant value to represent the total number of vertices, the maximum integer size to avoid overflow issues, a graph, and a matrix to perform memoization for the top-down recursion approach. We have then defined the function as travelling_salesman_problem() that accepts two parameters - the first parameter is iterable, and the second one is the bitmask. Inside this function, we have defined a base case for the recursion, which will execute only when the current and first bit is set in the mask, implying that all other nodes have already been visited. After that, we performed memorization and initialized the minimum cost as the maximum integer value. We then used the for-loop to iterate through all the nodes in the mask. We recursively calculated the cost of travelling the nodes in the mask except the selected one and then travelling back to starting node by taking the shortest possible path. For the main function, we have initialized the resultant cost as the maximum integer value and used the for-loop to iterate through the nodes of the graph and calculate the new minimum cost by calling the travelling_salesman_problem() function for that particular node and set the minimum cost value as the resultant cost. At last, we have printed the result for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Python

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Python Programming Language:

File: TSP.py

Output:

Minimum Cost : 90

Explanation:

In the above code snippet, we defined a constant value to represent the total number of vertices, a graph, and a matrix to perform memoization for the top-down recursion approach. We have then defined the function as travelling_salesman_problem() that accepts two parameters - the first parameter is iterable, and the second one is the bitmask. Inside this function, we have defined a base case for the recursion, which will execute only when the current and first bit is set in the mask, implying that all other nodes have already been visited. After that, we performed memorization and initialized the minimum cost as the maximum integer value. We then used the for-loop to iterate through all the nodes in the mask. We recursively calculated the cost of travelling the nodes in the mask except the selected one and then travelling back to starting node by taking the shortest possible path. For the main function, we have initialized the resultant cost as the maximum integer value and used the for-loop to iterate through the nodes of the graph and calculate the new minimum cost by calling the travelling_salesman_problem() function for that particular node and set the minimum cost value as the resultant cost. At last, we have printed the result for the users.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Time and Space Complexity of Travelling Salesman Problem Using Dynamic Programming Approach

  • The Time Complexity of the Travelling Salesman Problem using the Dynamic Programming Approach will be O(N2 * 2N), where O(N * 2N) are maximum number of unique sub-problems in recursion and O(N) for transition (through for-loop) in every nodes.
  • The Space Complexity of the Travelling Salesman Problem using the Dynamic Programming Approach will be O(N * 2N), where N is the number of nodes.

Solving Travelling Salesman Problem Using Greedy Approach

In the following approach, we will solve the problem using the steps mentioned below:

Step 1: First of all, we will create two primary data holders - The first data holder will be the list to store the indices of the cities in terms of the input matrix of distances between the cities, and the second one will be the array to store the result.

Step 2: For the second step, we will traverse through the given adjacency matrix for all the cities and update the cost by checking if the cost of reaching any city from the current city is lower than the current cost.

Step 3: At last, we will generate the minimum path cycle with the help of the above step and return their minimum cost.

Implementation of Greedy Approach to Solve Travelling Salesman Problem in Different Programming Languages

Now that we have successfully understood the above procedure to solve the Travelling Salesman Problem using Greedy Approach, it is time to see its implementation in different programming languages like C++, Java, and Python.

Code Implementation in C++

The following is the implementation of the Travelling Salesman Problem's Algorithm in the C++ Programming Language:

File: TSP.cpp

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we included the 'bits/stdc++.h' header file and used the standard namespace. We have then defined the function as travelling_salesman_problem(), which accepts a two-dimensional array as its parameter. Inside this function, we have defined some variables initializing them with some initial values. We then used the while loop to iterate through the graph and calculate the minimum cost. We have also included a break statement if the count exceeds the size of the graph. We updated the minimum cost value along with the route if the selected value from the graph is lower than the current minimum cost. We have also updated the total cost by adding the final minimum cost and setting the variables to their initial values. We then used the for-loop to generate the minimum path cycle by evaluating the total minimum cost and printed the result for the users. In the main function, we have defined the graph using the two-dimensional vector and called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Java

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Java Programming Language:

File: TSP.java

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we have imported everything from the 'java.util' library and defined the main class as TSP to solve the Travelling Salesman Problem. In this class, we have defined the function as travelling_salesman_problem(), which accepts a two-dimensional array as its parameter. Inside this function, we have defined some variables initializing them with some initial values. We then used the while loop to iterate through the graph and calculate the minimum cost. We have also included a break statement if the count exceeds the size of the graph. We updated the minimum cost value along with the route if the selected value from the graph is lower than the current minimum cost. We have also updated the total cost by adding the final minimum cost and setting the variables to their initial values. We then used the for-loop to generate the minimum path cycle by evaluating the total minimum cost and printed the result for the users. In the main function, we have defined the graph and called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Code Implementation in Python

The following is the implementation of the Travelling Salesman Problem's Algorithm in the Python Programming Language:

File: TSP.py

Output:

Minimum Cost : 90

Explanation:

In the above snippet of code, we have defined the main class as TSP to solve the Travelling Salesman Problem. In this class, we have defined the function as travelling_salesman_problem(), which accepts a two-dimensional list as its parameter. Inside this function, we have defined some variables initializing them with some initial values. We then used the while loop to iterate through the graph and calculate the minimum cost. We have also included a break statement if the count exceeds the size of the graph. We updated the minimum cost value along with the route if the selected value from the graph is lower than the current minimum cost. We have also updated the total cost by adding the final minimum cost and setting the variables to their initial values. We then used the for-loop to generate the minimum path cycle by evaluating the total minimum cost and printed the result for the users. In the main function, we have defined the graph and called the travelling_salesman_problem() function to find the minimum weight Hamiltonian cycle cost.

As a result, the minimum weight Hamiltonian cycle cost, i.e., 90, is printed for the users.

Time and Space Complexity of Travelling Salesman Problem Using Greedy Approach

  • The Time Complexity of the Travelling Salesman Problem using the Greedy Approach will be O(N2 * log N), where N is the number of cities.
  • The Space Complexity of the Travelling Salesman Problem using the Greedy Approach will be O(N).






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA