Breaking
Branch and Bound

Traveling salesman problem

Traveling salesman problem helps to find the shortest possible route that visits each city exactly once and returns to the origin city. The traveling salesman problem solves the given set of cities and distance between each pair of cities. Find the shortest route that visit each city exactly once and return to the origin of the city.

Write a program to give all the brute force approach to find the sorted path between the cities?

source Code

package com.dsacode.Algorithm.bruteforce;

import java.util.ArrayList;

public class TravellingSalesman {

@SuppressWarnings("unused")
private static ArrayList < Integer > bestRoute;

public static void bruteForceFindBestRoute(ArrayList < Integer > r, ArrayList < Integer > citiesNotInRoute) {
if(!citiesNotInRoute.isEmpty()) {
for(int i = 0; i < citiesNotInRoute.size(); i++) {
Integer justRemoved =  (Integer) citiesNotInRoute.remove(0);

@SuppressWarnings("unchecked")
ArrayList < Integer > newRoute = (ArrayList < Integer >) r.clone();

bruteForceFindBestRoute(newRoute, citiesNotInRoute);
}
}else{
if(isBestRoute(r))
bestRoute = r;
}

}

private static boolean isBestRoute(ArrayList < Integer > r) {
System.out.println(r.toString());
return false;
}

public static void main(String[] args) {
ArrayList < Integer > lst = new ArrayList < Integer >();
for (int i = 0; i < 3; ++i)
System.out.println("Number of items from the list: " + lst.toString());
ArrayList < Integer > route = new ArrayList < Integer >();
System.out.println("All the routes using Branch and bound : ");
bruteForceFindBestRoute(route, lst);
}
}

Output

Number of items from the list: [0, 1, 2]
All the routes using Branch and bound :
[0, 1, 2]
[0, 2, 1]
[1, 2, 0]
[1, 0, 2]
[2, 0, 1]
[2, 1, 0]