Solving TSP problem based on greedy algorithm (JAVA)

Source: Internet
Author: User

The previous time in the greedy algorithm, for example, so take the TSP to the operation, write a section to solve the algorithm code for the need, pay attention to the code to consider readability from the most easy to understand the angle of writing, no optimization, there is a need to self-optimization!

First, the TSP problem

The TSP problem (travelling salesman problem) is one of the famous problems in the field of mathematics, which is the traveling salesman problem and the traveling salesman problem. Suppose there is a travel merchant to visit N cities, he must choose the path to go, the limit of the path is that each city can only visit once, and finally return to the original city of departure. The path selection target is the minimum required path distance for all paths.

TSP problem is a combinatorial optimization problem. This problem can be proven to have NPC computational complexity. TSP problem can be divided into two categories, one is symmetric tsp (symmetric tsp) and the other is asymmetric (asymmetric tsp). All TSP problems can be described by a graph:

v={c1, c2, ..., CI, ..., cn},i =..., n, is a collection of all cities. ci denotes the First city,N is the number of cities;

e={(R, s): R,s∈v} is a collection of connections between all cities;

C = {Crs:r,s∈v} is a cost metric for connections between all cities (typically the distance between cities);

If CRS = CSR, then the TSP problem is symmetric, otherwise asymmetric.


A TSP problem can be expressed as:

The solution traversal graph G = (V, E, C), all nodes once and go back to the starting node, making the path to connect these nodes the lowest cost.

Second, greedy algorithm

Greedy algorithm, also known as greedy algorithm (school old professors like to call greedy algorithm), is a commonly used to solve the optimization problem of a simple, rapid algorithm. The greedy algorithm always makes the best choice at present, and every one of them is the best choice in the current state, namely the greedy choice, and hopes to get the optimal solution of the problem by the greedy choice each time. It must be noted that the greedy algorithm does not have the overall optimal solution to all problems, the greedy strategy chosen must have no effect, that is, the process after a state does not affect the previous state, only related to the current state.

1. Basic idea of greedy algorithm

Trigger a gradual approximation of a given target from one of the initial solutions of the problem to obtain a better solution as quickly as possible. The algorithm stops when a step in an algorithm can no longer move forward. The approximate steps are as follows:

1) Establish a mathematical model to describe the problem;
2) Divide the problem of solving into several sub-problems
3) to solve each sub-problem, the local optimal solution of sub-problem is obtained.
4) A solution to the problem of local optimal solution synthesis of the problem

2. The implementation framework of greedy algorithm

Greedy algorithm has no fixed algorithm framework, the key of algorithm design is the choice of greedy strategy, and the premise of greedy strategy is: local optimal strategy can lead to global optimal solution.

Starting from an initial solution of a problem;
While (one step forward for a given total target)
{
A solution element of the feasible solution is obtained by using the feasible decision;
}
A feasible solution to the problem of the combination of all solution elements;

3. Problems of greedy algorithm

1) The Final solution is not guaranteed to be the best;
2) can not be used to find the biggest pee problem;
3) can only be used in the case of certain constraints, such as greedy strategy must have no effect.

4, the typical greedy algorithm uses the domain

Horse tread Board, backpack, boxing, etc.

Three, greedy algorithm solves TSP problem

Greedy strategy: In the current node to traverse all the next node can reach, select the closest node as the next node. The basic idea is to traverse all reachable nodes from one node, select the closest node as the next node, then mark the current node as past, the next node as the current node, repeat the greedy policy, and so on until all nodes are marked as the end of the node.

We use the TSP problem still comes from tsplib on the att48, this is a symmetric tsp problem, the city size is 48, its optimal value is 10628. The distance calculation method is as follows:

OK, here's the exact code:

Package Noah;import Java.io.bufferedreader;import Java.io.fileinputstream;import java.io.ioexception;import Java.io.inputstreamreader;public class TXTSP {private int citynum;//City number private int[][] distance;//distance matrix private int[] C olable;//represents the column, also indicates whether to walk, pass 0private int[] row;//representative row, selected over 0public txtsp (int n) {citynum = n;} private void init (String filename) throws IOException {//Read data int[] x;int[] y; String Strbuff; BufferedReader data = new BufferedReader (new InputStreamReader (new FileInputStream (filename));d istance = new int[ citynum][citynum];x = new Int[citynum];y = new Int[citynum];for (int i = 0; i < Citynum; i++) {//read one row of data, data format 1 6734 145 3strbuff = Data.readline ();//character split string[] strcol = Strbuff.split (""); X[i] = integer.valueof (strcol[1]);//x coordinate y[i] = Inte Ger.valueof (strcol[2]);//y-coordinate}data.close ();//, for specific problems, distance calculation method is not the same, here is the case of att48, it has 48 cities, the distance calculation method is pseudo-Euclidean distance, The optimal value is 10628for (int i = 0; i < cityNum-1; i++) {distance[i][i] = 0;//diagonal is 0for (int j = i + 1; j < Citynum; J + +) {Double Rij = Math.sqrt (((X[i]-x[j]) * (X[i]-x[j]) + (Y[i]-y[j])/10.0);//rounding, rounding int y[i = (int) Mat H.round (Rij), if (Tij < Rij) {Distance[i][j] = Tij + 1;distance[j][i] = distance[i][j];} else {distance[i][j] = Tij;dist Ance[j][i] = Distance[i][j];}} Distance[citynum-1][citynum-1] = 0;colable = new Int[citynum];colable[0] = 0;for (int i = 1; i < Citynum; i++) {col Able[i] = 1;} row = new Int[citynum];for (int i = 0; i < Citynum; i++) {row[i] = 1;}} public void Solve () {int[] temp = new Int[citynum];  String path= "0"; int s=0;//computes the distance int i=0;//current node int j=0;//next node//default starting from 0 while (row[i]==1) {//Copy line for (int k = 0; k < citynum; k++) {Temp[k] = Distance[i][k];//system.out.print (temp[k]+ "");} System.out.println ();//Select the next node, the requirements are not already traversed, and with I different j = selectmin (temp);//Find the next node row[i] = 0;//row 0, indicating that the colable[j is selected) = 0;// Column 0, indicating has traversed path+= "--" + j;//system.out.println (i + "--" + j);//system.out.println (Distance[i][j]); s = s + distance I [j];i = j;//The current node points to the next node}system.out.println("Path:" + path); SYSTEM.OUT.PRINTLN ("Total Distance:" + s);} public int selectmin (int[] p) {Int j = 0, M = p[0], k = 0;//look for the first available node, note the last search, no available node while (colable[j] = = 0) {J++;//system. Out.print (j+ ""); if (j>=citynum) {//No nodes are available, the description is closed, the last is *-->0m = p[0];break;//, or direct return 0;} Else{m = P[j];}} Scan backward from available node J to find out the minimum distance node for (; J < Citynum; J + +) {if (colable[j] = = 1) {if (M >= p[j]) {m = P[j];k = J;}}} return k;} public void Printinit () {System.out.println ("Print begin ..."); for (int i = 0; i < Citynum; i++) {for (int j = 0; J < Citynum; J + +) {System.out.print (Distance[i][j] + "");} System.out.println ();} System.out.println ("Print end ...."); public static void Main (string[] args) throws IOException {System.out.println ("Start ..."); TXTSP ts = new TXTSP, Ts.init ("C://data.txt");//ts.printinit (); Ts.solve ();}}

Solution Result:

Iv. Summary

Single from the results of the solution, I personally can still accept the solution, but think about it, in fact, there is too much luck in the solution results in the inside, greedy algorithm is after all greedy algorithm, only slow, rather than a long-term solution, the problem of the model, the parameters of the greedy algorithm to solve the results of a decisive role, This is unacceptable to some extent, so intelligent humans invented a variety of intelligent algorithms (also called heuristics), but in my opinion the so-called intelligent algorithm is essentially greedy algorithm and randomized algorithm, such as the traditional genetic algorithm used in the selection strategy is a typical greedy choice, It is the combination of these greedy algorithms and random algorithms that we see today in a variety of intelligent algorithms.

Reprint Please specify: http://blog.csdn.net/wangqiuyun/article/details/38680151


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.