import java.util.
InputMismatchException;
import java.util.Scanner;
import java.lang.Math;
/**
* Write a description of class TSPn here.
* @author (Raja kedia)
* @version (version 1.1)
*/
public class TSPn
private int noNodes; //to store no. of city
public TSPn(){
noNodes = 0;
public void tsp(double amat[][]){ //amat is the distance matrix
noNodes = amat[1].length - 1;
System.out.println("No. of Cities: "+noNodes + "\t");
int[] visit = new int[noNodes + 2];
visit[0] = 1; //to store visited cities
int e=0 ,pos = 0,i,k=1;
double min = 1000,sum=0;
System.out.print(1 + "\t");
while(k < noNodes){ //to traverse each city
i=1;
min = 1000;
while(i < noNodes){ //finding minimum distance between the cities
if(visit[i] != 1){ //check whether city is visited or not
if(min > amat[e][i]){
min = amat[e][i]; //store minimum distance
pos = i; //storing city position
i++;
if(min>0){
sum += min; //adding total distance covered by salesman
visit[pos] = 1; //making the unvisited city visited
e = pos; //sending salesman to next destination
System.out.print((pos+1) + "\t"); //printing city that is visited
k++;
sum+=amat[0][pos];
System.out.println("1");
System.out.printf("Total Distance: %.2f ",sum);
public static double distance(int x1,int y1,int x2,int y2){ //to calculate distance between two
coordinate
float k = (float)Math.pow((x2 - x1),2) + (float)Math.pow((y2 - y1),2);
double s = Math.sqrt(k);
return s;
}
public void matrix(double amat[][] , int smat[][], int n){ //to find the distance matrix from the
coordinate matrix
int i,j;
for(i=0;i<n;i++){
for(j=i;j<n;j++){
amat[i][j] = distance(smat[i][0],smat[i][1],smat[j][0],smat[j][1]);
public static void calculate(int smat[][],int n,double amat[][]){
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(amat[i][j] != amat[j][i])
amat[j][i] = amat[i][j];
System.out.println();
for(i=-1;i<n;i++){
for(j=-1;j<n;j++){
if(i == -1){
System.out.print((j+1)+"\t");
else{
if(j == -1)
System.out.print((i+1)+"\t");
else
System.out.printf("%.2f \t",(float)amat[i][j]); //printing the distance matrix
System.out.println();
TSPn ts = new TSPn();
System.out.println("The city are as follows: ");
ts.tsp(amat);
System.out.println("\n");
public static void main(String args[]){ //main function
int noNodes,i,j;
Scanner s = null;
TSPn ts = new TSPn();
try{
System.out.print("Enter no.of City: "); //input no. of city
s = new Scanner(System.in);
noNodes = s.nextInt();
int n = noNodes;
int smat[][] = new int[n+1][2]; //to store coorinate
double amat[][] = new double[n+1][n+1]; //to store distance
System.out.println("Enter X and Y for each city: ");
for(i=0;i<n;i++){
smat[i][0] = s.nextInt();
smat[i][1] = s.nextInt();
}
for(i=0;i<n;i++){
int x=smat[0][0];
int y=smat[0][1];
for(j=1;j<n;j++){
smat[j-1][0]=smat[j][0];
smat[j-1][1]=smat[j][1];
smat[n-1][0]=x;
smat[n-1][1]=y;
ts.matrix(amat,smat,n);
ts.calculate(smat,n,amat);
catch(InputMismatchException inputMismatch){
System.out.println("Wrong format"); // input error
s.close(); //closing of scanner class