Sunday, November 5, 2017

Travelling Salesman Problem

Tags

Question:

Code:
Write a program to find minimum route for a newspaper distributer of your locality using Greedy algorithm. 

public class Dmain {

    public static void main(String[] nt){

        int n=5;
        int[][] c={{0,3,Integer.MAX_VALUE,7,Integer.MAX_VALUE,3},{3,0,2,Integer.MAX_VALUE,6,Integer.MAX_VALUE},{Integer.MAX_VALUE,2,0,2,5,Integer.MAX_VALUE},
                {7,Integer.MAX_VALUE,2,0,1,Integer.MAX_VALUE},
                {Integer.MAX_VALUE,6,5,1,0,4},
                {3,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,4,0}
                    };

        /*int[][] d={                {1,2,3,4},                {5,6,7,8},                {3,4,5,6},                {9,8,4,3}        };*/
        System.out.println("Shorest Path is : "+find(c));
    }

    static StringBuffer find(int[][] c){
        StringBuffer buffer=new StringBuffer();
        boolean [] present=new boolean[c.length];
        for(int i=0;i<c.length;i++){
            present[i]=false;
        }
        int count=1,node=0,cost=0,previous=0;
        present[node]=true;
        while(count!=c.length+1){
            int min=Integer.MAX_VALUE,minindex=0;
            for(int i=0;i<c[node].length;i++){
                if(present[i]==false && min>c[node][i]){
                        min=c[node][i];
                        minindex=i;
                }
            }
            present[minindex]=true;
            if(min!=Integer.MAX_VALUE){ cost+=min;}
            buffer.append((node+1)+"->");
            previous=node;
            node=minindex;
            count++;
        }
        buffer.append("1"+"\nMinimum Cost Is : "+(cost+c[previous][0]));
        return buffer;
    }

}

Output: