Algorithmic note _018: Travel quotient problem (Java)

Source: Internet
Author: User

Directory

1 Problem Description

2 Solutions

2.1 Brute Force method

  1 problem description

What is the travel business problem? according to the non-professional argument, this question requires finding a N The shortest path between a given city, so that we can only access it once for each city before returning to the triggering city. so the problem can be expressed as the problem of finding the shortest Hamiltonian circuit of a graph. (Hamiltonian loop: defined as a loop that crosses only once for each vertex of the graph)

It is easy to see that the Hamiltonian loop can also be defined as a sequence of n+1 adjacent vertices v1,v2,v3,..., vn,v1 . Where the first and last vertices of the sequence are the same, and the other n-1 vertices are distinct. And, without losing its generality, it can be assumed that all loops start and end at the same specific vertex. Therefore, you can get all the travel routes by generating a combination of n-1 cities, calculate the lengths of these lines, and then find the shortest route. is a small-scale instance of the problem, and its solution is obtained by using this method, as follows:

Figure 1 Solving the traveling quotient problem using brute force method

2 Solutions 2.1 Brute Force method

here, the brute force method is used to solve the problem of traveling quotient, which takes 4 cities and defines the distances between cities. PS: This distance uses a two-dimensional array initialization definition, The distance here is defined according to the distance shown in Figure 1). Here is mainly in the experience of using brute force method to solve the problem of the idea, such as to enrich the general scale of the problem, but also ask you to modify the DA. You can refer to the reference links at the end of the article, as well as the relevant code annotations, for areas that you do not understand in your code ~

The specific code is as follows:

 PackageCom.liuzhen.chapterThree; Public classTravelingsalesman { Public intCount = 0;//defines a global variable that is used to calculate the number of currently-traveled scenarios, initialized to 0     Public intmindistance = 100;//defines the shortest distance to complete a walk scheme, initialized to (ps:100 here represents a much larger distance than the actual)     Public int[] distance = {{0,2,5,7},{2,0,8,3},{5,8,0,1},{7,3,1,0}};//The path-dependent distance length of the graph using the two-dimensional array    /** Start is the position to begin sorting * Step is currently walking position * N is the total number of positions that need to be sorted * Max is n! value*/     Public voidArrange (int[] A,intStartintStepintNintMax) {        if(step = = N) {//When the location you are walking equals the total number of cities++count;//Count self-increment 1 per walk-through scenarioPrintArray (A);//output Travel route scheme and its total distance        }        if(Count = =Max) System.out.println ("Completed all Walk plan!!! , the shortest path distance is: "+mindistance); Else{             for(inti = Start;i < n;i++){                   /*The number of the number I and the subsequent digital exchange will be able to get a new arrangement, so that can get n! different sorting scheme * (PS: In this code, the execution order of recursion is a little abstract, the specific explanation see my other blog:) *Algorithm Note _017: A discussion of recursive execution order (Java)
*/Swaparray (a,start,i); Arrange (A,start+1,step+1, N,max);            Swaparray (A,i,start); }        }    }        //swap values in two positions in an array     Public  voidSwaparray (int[] A,intPintq) {        inttemp =A[p]; A[P]=A[q]; A[Q]=temp; }        //outputs the sequence of array A and outputs the distance from the current walking sequence, and obtains the shortest distance in the completed walk scheme     Public voidPrintArray (int[] A) {         for(inti = 0;i < a.length;i++)//outputs the sequence of the current walk schemeSystem.out.print (a[i]+ ""); intTempdistance = distance[a[0]][a[3]];//This is because, ultimately, to return to the city of origin, so the total distance to add the last arrival of the city to the starting point of the city's distance         for(inti = 0;i < (a.length-1); i++)//output distance from the current walk schemeTempdistance + = Distance[a[i]][a[i+1]]; if(Mindistance > Tempdistance)//returns the shortest walking distance of the currently completed scenarioMindistance =tempdistance; System.out.println ("Walking distance sum:" +tempdistance); }         Public Static voidMain (string[] args) {int[] A = {0,1,2,3}; Travelingsalesman Test=NewTravelingsalesman (); Test. Arrange (A,0,0,4,24);//here max = 4!=24    }}

Operation Result:

0  1  2  3    total Walking distance: 1 3 2 walking distance total: 2  1 3    total walking distance: 230  2  3  1    total walking distance:  3  2  1    total walking distance:  3    1 2 Total walking distance: 231  0  2  3    total walking distance: 111  0  3  2    total walking distance: 181  2  0  3    Total Walking distance: 231  2  3  0    total walking distance: 181  3  2  0    Total walking distance: 111  3  0  2    Total walking distance: 232  1  0  3    total walking distance: 182  1  3  0    total walking distance: 232  0  1  3    Total walking distance: 0 3 1 Total walking distance:    232  3 0  1    total walking distance: 182  3  1  0    total walking distance: 113  1  2  0    total walking distance: 233  1  0  2    total walking distance: 113  2  1  0    Total walking distance: 183  2  0  1    total walking distance: 113  0  2  1    total walking distance: 233  0  1  2    total walking distance: completed all Walk plan!!! , the shortest path distance is:11

Resources:

1. "Basic algorithm design and analysis" brute force method to solve the problem of traveling business

Algorithmic note _018: Travel quotient problem (Java)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.