Solving the shortest total distance between cities is a very practical problem with the following effect:
An area of N cities, how to choose a route so that the total distance between cities shortest?
1. Shortest total distance algorithm
First to analyze the above problems. N cities in a region form a traffic map that can be used to describe the problem with the following relationship:
- Each city represents a vertex in the diagram.
- The edges between the two vertices are the paths between the two cities, and the weights of the edges represent the distances between cities.
Thus, the problem of solving the shortest total distance between cities is attributed to the minimum spanning tree problem of the graph.
2. Minimum spanning tree algorithm (prim algorithm)
//minimum spanning tree algorithm Static voidprimgraph (Graphmatrix GM) {inti,j,k,min,sum; int[] weight=New int[Graphmatrix.maxnum];//Weighted Value Char[] vtempx=New Char[Graphmatrix.maxnum];//temporary vertex informationSum=0; for(I=1;I<GM. vertexnum;i++) {//save a row of data in the adjacency matrixWEIGHT[I]=GM. Edgeweight[0][i]; if(weight[i]==MaxValue) {Vtempx[i]=(Char) NoL; }Else{Vtempx[i]=GM. VERTEX[0];//adjacency Vertex}} vtempx[0]=used;//selectionweight[0]=MaxValue; for(I=1;I<GM. vertexnum;i++) {min=WEIGHT[0];//Minimum weight valuek=i; for(J=1;J<GM. vertexnum;j++){ if(weight[j]<min&&vtempx[j]>0) {//to find unused edges with a smaller weighted valueMIN=WEIGHT[J];//Save weight valueK=j;//Save adjacency Point ordinal}} sum+=min;//Weighted value accumulationSystem.out.printf ("(%c,%c),", VTEMPX[K],GM. Vertex[k]);//output spanning tree one edgevtempx[k]=used;//selectionweight[k]=MaxValue; for(J=0;J<GM. vertexnum;j++) {//re-select the minimum edge if(GM. Edgeweight[k][j]<weight[j]&&vtempx[j]!=0) {Weight[j]=GM. EDGEWEIGHT[K][J];//Weighted Valuevtempx[j]=GM. VERTEX[K]; }}} System.out.printf ("\ n The total weight of the minimum spanning tree is:%d\n", sum); }
3. The program code example is as follows:
Packagecom.cn.datastruct;ImportJava.util.Scanner;//solving the shortest total distance between cities Public classPrim {//defining the adjacency matrix diagram structure Static classgraphmatrix{Static Final intmaxnum=20;//maximum number of vertices in a graph Char[] vertex=New Char[Maxnum];//Save vertex information (ordinal or letter) intGType;//type of diagram (0: No-map, 1: Forward graph) intVertexnum;//the number of vertices intEdgenum;//the number of edges int[] Edgeweight =New int[Maxnum] [Maxnum];//the right to save the edge int[] Istrav =New int[Maxnum];//Traverse Flag } Static Final intmaxvalue=65535;//Maximum value (can be set to a maximum integer) Static Final intUsed=0;//Selected vertices Static Final intNol=-1;//non-contiguous vertices StaticScanner input=NewScanner (system.in); //creating adjacency matrix graphs Static voidcreategraph (Graphmatrix GM) {inti,j,k; intWeight//Rights CharESTARTV,EENDV;//The starting vertex of the edgeSystem.out.printf ("Input each vertex information in the graph \ n"); for(I=0;I<GM. vertexnum;i++) {//input verticesSystem.out.printf ("%d vertices:", i+1); GM. Vertex[i]= (Input.next (). ToCharArray ()) [0];//in an array element that is saved to each vertex} System.out.printf ("Enter the vertices and weights that make up each edge: \ n"); for(K=0;K<GM. edgenum;k++) {//Enter the information for the EdgeSystem.out.printf ("section%d:", k+1); Estartv=input.next (). CharAt (0); EENDV=input.next (). CharAt (0); Weight=Input.nextint (); for(i=0; ESTARTV!=GM. vertex[i];i++);//find a starting point in an existing vertex for(j=0; EENDV!=GM. vertex[j];j++);//find the end point in an existing vertexGM. Edgeweight[i][j]=weight;//the corresponding position holds the weight value, indicating that there is an edge if(GM. gtype==0) {//If the graph is notGM. edgeweight[j][i]=weight; } } } //Clear the Matrix Static voidcleargraph (Graphmatrix GM) {inti,j; for(I=0;I<GM. vertexnum;i++){ for(J=0;J<GM. vertexnum;j++) {GM. EDGEWEIGHT[I][J]=maxvalue;//sets the value of each element in the matrix to MaxValue } } } //Output adjacency Matrix Static voidoutgraph (Graphmatrix GM) {inti,j; for(J=0;J<GM. vertexnum;j++) {System.out.printf ("\t%c", GM. VERTEX[J]);//output vertex information on the first line} System.out.println (); for(I=0;I<GM. vertexnum;i++) {System.out.printf ("%c", GM. Vertex[i]); for(J=0;J<GM. vertexnum;j++){ if(GM. Edgeweight[i][j]==maxvalue) {//if the weighted value is the maximum valueSystem.out.printf ("\tz");//Infinity is represented by Z}Else{System.out.printf ("\t%d", GM. EDGEWEIGHT[I][J]);//weight of the output edge}} System.out.println (); } } //minimum spanning tree algorithm Static voidprimgraph (Graphmatrix GM) {inti,j,k,min,sum; int[] weight=New int[Graphmatrix.maxnum];//Weighted Value Char[] vtempx=New Char[Graphmatrix.maxnum];//temporary vertex informationSum=0; for(I=1;I<GM. vertexnum;i++) {//save a row of data in the adjacency matrixWEIGHT[I]=GM. Edgeweight[0][i]; if(weight[i]==MaxValue) {Vtempx[i]=(Char) NoL; }Else{Vtempx[i]=GM. VERTEX[0];//adjacency Vertex}} vtempx[0]=used;//selectionweight[0]=MaxValue; for(I=1;I<GM. vertexnum;i++) {min=WEIGHT[0];//Minimum weight valuek=i; for(J=1;J<GM. vertexnum;j++){ if(weight[j]<min&&vtempx[j]>0) {//to find unused edges with a smaller weighted valueMIN=WEIGHT[J];//Save weight valueK=j;//Save adjacency Point ordinal}} sum+=min;//Weighted value accumulationSystem.out.printf ("(%c,%c),", VTEMPX[K],GM. Vertex[k]);//output spanning tree one edgevtempx[k]=used;//selectionweight[k]=MaxValue; for(J=0;J<GM. vertexnum;j++) {//re-select the minimum edge if(GM. Edgeweight[k][j]<weight[j]&&vtempx[j]!=0) {Weight[j]=GM. EDGEWEIGHT[K][J];//Weighted Valuevtempx[j]=GM. VERTEX[K]; }}} System.out.printf ("\ n The total weight of the minimum spanning tree is:%d\n", sum); } Public Static voidMain (string[] args) {Graphmatrix GM=NewGraphmatrix ();//defines a diagram that holds the structure of an adjacency table Charagain; String go; System.out.println ("Find the smallest spanning tree!" "); Do{System.out.print ("Please enter the type of build diagram first:"); GM. GType=input.nextint ();//Types of graphsSystem.out.print ("Number of vertices of the input graph:"); GM. Vertexnum=input.nextint ();//number of vertices of the input graphSystem.out.print ("Number of sides of the input graph:"); GM. Edgenum=input.nextint ();//Enter the number of image edgesCleargraph (GM);//Clear DiagramCreategraph (GM);//graphs that generate adjacency table structuresSystem.out.print ("The edge of the minimum spanning tree is:"); Primgraph (GM); System.out.println ("\ nyou keep playing (y/n)?"); Go=Input.next (); } while(Go.equalsignorecase ("Y")); System.out.println ("The game is over!" "); }}
Shortest total distance between cities (minimum spanning tree algorithm)