×

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling Salesman's Problem is the Hamiltonian Cycle.

The fundamental contrast between TSP and the Hamiltonian cycle is that within the other, we must determine whether such a tour that stops in each city precisely once already exists. A Hamiltonian cycle is always present in the Traveling Salesman Problem since the graph is complete. The goal is to identify a Hamiltonian cycle with the least weight.

Solution

The most well-known computing problem is the traveling salesman problem. We can apply a brute-force strategy to compare every trip and choose the best one. A graph has (n - 1) vertices for every n vertices. A multitude of potential outcomes.

Although no polynomial time algorithm exists, dynamic programming can achieve the solution in less time.

Consider the graph G = (V, E), which consists of a collection of cities as nodes and a set of weighted edges as edges. The connection between vertices u and v is shown by the edge e(u, v). Vertex u and v are separated by a distance called d(u, v), which must not be negative.

Consider that after visiting a few cities, we are now in city j, having started at city 1. So, this is only a portion of the tour. Since j will determine which towns are the most convenient to visit next, we must unquestionably know it. To avoid repetition, we must also be aware of every city we have visited. As a result, this is the right sub-problem.

Let C(S, j) be the lengths of the Shortest Distance traversing each node in S exactly once, beginning at 1, and ending at j, for a subgroup of cities S 1, 2, 3,..., n that contains 1, and j in S.

Considering that the path cannot continue and terminate at 1, we define C(S, 1) = when |S| > 1.

Let's break C(S, j) into more manageable subproblems. Starting at 1 and ending at j is what we need to do. The city should choose in the following way.

C(S,j)=minC(S-{j},i)+d(i,j) where i∈Sandi≠j

c(S,j)=minC(s-{j},i)+d(i,j) where I∈Sandi≠j

Algorithm

C ({1}, 1) = 0 
for s = 2 to N, do 
   for all the subsets of Sub Є {1, 2, 3, … , N} of size S and containing 1 
      C (Sub, 1) = ∞ 
   for all j Є S and j ≠ 1 
      C (Sub, j) = min {C (Sub– {j}, i) + d(i, j) for i Є Sub and i ≠ j} 
return minj C ({1, 2, 3, …, N}, j) + d(j, i) 

Implementing the Traveling Salesman Problem

We employ the subsequent stages to implement the TSP program in Java:

  • We look at a city as the beginning and the end. Because the route is circular, we can start in any city.
  • According to the DFS method, we begin by traversing from the source to its nearby nodes.
  • Determine the price of each traversal, maintain a note of the lowest price, and continually update the value of the minimum price stored value.
  • Return the permutation with the lowest cost in the end.

Filename: SalesmanProblem.java

// Java program for salesman problem
//importing required packages
import java.util.*;   
import java.io.*;   
import java.util.Scanner;  
// A class is created to implement code   
class SalesmanProblem
{  
    // the method findHamiltonianCycles() for finding the cycles of all cities
    static int findHamiltonianCycles(int[][] distances, boolean[] visitCities, int currPosition, int city, int counts, int costs, int hamiltonianCycles)   
    {  
    
        if (counts == city && distances[currPosition][0] > 0)   
        {  
            hamiltonianCycles = Math.min(hamiltonianCycles, costs + distances[currPosition][0]);  
            return hamiltonianCycles;  
        }  
    
        // the step for interacting over the paths
        for (int i = 0; i < city; i++)   
        {  
            if (visitCities[i] == false && distances[currPosition][i] > 0)   
            {  
                // stores if it is visited
                visitCities[i] = true;  
                hamiltonianCycles = findHamiltonianCycles(distances, visitCities, i, city, counts + 1, costs + distances[currPosition][i],                     
                  hamiltonianCycles);  
                // The node which is not visited is marked  
                visitCities[i] = false;  
            }  
        }  
        return hamiltonianCycles;  
    } 
    // main section of the program
    public static void main(String[] args)  
    {  
        int city;  
        // The Scanner class object is created for gettig the input from the user as distance
        Scanner sca = new Scanner(System.in);  
        // Entering the number of cities 
        System.out.println("Enter the total number of cities:");  
        city = sca.nextInt();  
        // reading the cities’ distances
        int distances[][] = new int[city][city];  
        for( int i = 0; i < city; i++){  
            for( int j = 0; j < city; j++){  
                System.out.println("The Distance between the cities "+ (i+1) +" to cities"+ (j+1) +": ");  
                distances[i][j] = sca.nextInt();  
            }  
        }  
        // A boolean array is created for storing the boolean values for storing the cities visited or unvisited
        boolean[] visitCities = new boolean[city];  
        // The first city is marked as visited 
        visitCities[0] = true;  
        int hamiltonianCycles = Integer.MAX_VALUE;  
        // call findHamiltonianCycles() method that returns the path, which consists of minimal path
        hamiltonianCycles = findHamiltonianCycles(distances, visitCities, 0, city, 1, 0, hamiltonianCycles);  
        // displays the cycle which contains minimum distance
        System. out.println(“The minimum distance is: ”+hamiltonianCycles);  
    }  
}  

Output

Enter the total number of cities:
5
The Distance between the cities 1 to cities1: 
23
The Distance between the cities 1 to cities2: 
18
1The Distance between the cities 1 to cities3:
5
The Distance between the cities 1 to cities4: 
35
The Distance between the cities 1 to cities5: 
12
The Distance between the cities 2 to cities1: 
45
The Distance between the cities 2 to cities2: 
124
The Distance between the cities 2 to cities3: 
34
1The Distance between the cities 2 to cities4: 
8
2The Distance between the cities 2 to cities5: 
9
The Distance between the cities 3 to cities1: 
34
The Distance between the cities 3 to cities2: 
56
The Distance between the cities 3 to cities3: 
3
The Distance between the cities 3 to cities4: 
23
The Distance between the cities 3 to cities5:
23
The Distance between the cities 4 to cities1: 
6
The Distance between the cities 4 to cities2: 
34
The Distance between the cities 4 to cities3: 
89
The Distance between the cities 4 to cities4: 
35
The Distance between the cities 4 to cities5: 
64
The Distance between the cities 5 to cities1: 
91
The Distance between the cities 5 to cities2: 
25
The Distance between the cities 5 to cities3: 
39
The Distance between the cities 5 to cities4: 
54
The Distance between the cities 5 to cities5: 
49
The minimum distance is:67

Time complexity: O(N!)

The node will contain the n possibilities; the second will contain n-1 possibilities, and so on.

Space Complexity: O(N)


Related Topics

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.