Java Practice Dijkstra algorithm to find the shortest path distance

Source: Internet
Author: User

Objective

The Dijkstra algorithm is used to specify the shortest distance from vertices to other vertices, time complexity O (n^2), which is said to use heap optimization to O (log N), but not yet.
Its characteristic is that (to me) it is very easy to find the path, and the corresponding distance.
Defects are also present, and this algorithm cannot handle negative weights. That is, when the distance is negative, it hangs.
This article also refers to the "Aha, algorithm"

In addition, personal feeling code may be wrong, but also look for guidance.

function implementation

Enter a vertex

Output path
The distance between the output and the path
If an unreachable vertex is present, the output vertex is not reachable

Chinese version Reference


Corresponding two-dimensional array

     {0, 1, 12, INF, INF, INF},     {INF, 0, 9, 3, INF, INF},     {INF, INF, 0, INF, 5, INF},     {INF, INF, 4, 0, 13, 15},     {INF, INF, INF, INF, 0, 4},     {INF, INF, INF, INF, INF, 0}
/** * Dijkstra Algorithm * * Specify a vertex to find the shortest path to each vertex * Step 1: * Select a vertex, such as Vertex 1 * Use Boolean array to record mark[1] = true; * indicates already shortest * Step 2: * Traverse each vertex to reach the length of vertex 1, cannot reach to infinity, to itself 0 * use a one-dimensional array with the same number of vertices to save all distances, at this time estimate distance * estimate distance dis array Store the [vertex 1], the distance to the other vertices * record the nearest vertex 1 (shortest distance) vertex, that is, the smallest number in dis, but cannot be 0 * Here the 2nd vertex distance vertex 1 nearest, so choose to reach Vertex 2, when Vertex 2 has determined the distance vertex 1 shortest * dis: [0 1 inf INF] * STEP 3: * Select Enter Vertex 2 * Indicates Vertex 2 is already the shortest, use Boolean array record mark[2] = true; * Traverse each vertex to reach the length of vertex 2, compare it to the estimated distance in dis, and the update of the estimated distance is less than the distance of the estimate. * Vertex 2 to Vertex 4 is 3 * The distance from Vertex 2 to Vertex 3 is 9 * * Vertex 1 to vertex 2 distance The distance of 1 * Vertex 2 to Vertex 3 is 9 * Added up is the shortest distance from Vertex 1 to vertex 4:10 * Smaller than the original, update estimated vertex 3 distance * dis: [0 1 inf INF] * * Vertex 2 to The distance from Vertex 4 to 3 * Vertex 1 to Vertex 2 is 1 * Added up is the shortest distance from Vertex 1 to vertex 4:4 * Smaller than original, estimated distance to update vertex 4 * DIS: [0 1 inf INF] * * Find out Nearest to Vertex 1, the shortest vertex is not determined * i.e. mark[n] = False, with the lowest value. * Here mark[1], mark[2] are true, after elimination, the value of the smallest is 4, select it * Step 4: * Select INTO the vertex 4 * indicates that Vertex 4 is already the shortest, using a Boolean array record mark[4] = true; * Traverse each vertex to reach the length of vertex 4, and estimate the distance from disCompared to the updated * after the estimated distance, the distance between the vertices 4 to 3 is 4 * The distance from Vertex 4 to vertex 5 is 13 * Vertex 4 to Vertex 6 distance is 15 * * Vertex 1 to vertex 4 distance is 4 * distance Add, Get * dis: [0 1 8 4 17 19] * Exclude vertices 1, 2, 4 to find the nearest vertex, is the vertex 3 * Step N: * Repeat Select the nearest vertex * Enter, and mark the shortest * Find a new distance and update the estimated distance * exclude the identified vertices and look for the minimum numeric vertex again */
Code implementation
 Public classDijkstrademo {Static intINF = About;Static int[] arr =New int[][] {            {0,1, A, INF, INF, INF}, {INF,0,9,3, INF, INF}, {INF, INF,0Inf5, INF}, {INF, INF,4,0, -, the}, {INF, INF, INF, INF,0,4}, {INF, INF, INF, INF, INF,0}    }; Public Static void Main(string[] args) {intPoint =1; System. out. println ("Starting point is"+ point);        Dijkstra (point); System. out. println (); Point =2; System. out. println ("Starting point is"+ point);    Dijkstra (point); } Public Static void Dijkstra(intPoint) {//Vertex-1 corresponds to the position of the angle markpoint--;//Vertex count        intn = arr.length;//To mark vertices that have been identified as the shortest distanceBoolean[] Mark =NewBoolean[n];//store its position in the array at the shortest distance        intNextmin = point;//To record the shortest distance found        intNextmindis;//position of the currently entered vertex in the array        intCurmin = point;//If it is not reachable, it should not be recordedBoolean flag =true;//Storage estimated distance        int[] dis =New int[n];//Initialize estimated distanceInitarray (Dis, point);//Record traversal times        intCount =0;//record path        int[] Path =New int[n];intTail =0; while(true) {//The currently selected vertex, marked as trueMark[curmin] =true; Nextmindis = INF;//per selection, self-incrementcount++;//If flag is false, there is an unreachable vertex and it does not have to be stored as one of the paths            if(flag) {path[tail++] = curmin +1; Flag =false; }//The number of vertices selected is already all vertices and can be written for I<n .            if(count = = N) { Break; }//system.out.println ("--------------------------------------");             for(inti =0; I < n; i++) {//Compare the estimated distance of vertex I to the distance from the previous shortest distance vertex to vertex i                //Take the smaller ones                if(Dis[i] > Dis[curmin] + arr[curmin][i])                    {Dis[i] = Dis[curmin] + arr[curmin][i]; Flag =true; System. out. println ("Vertex"+ (curmin+1) +"reach Vertex"+ (i+1) +", Distance"+ dis[i]); }//Get updated vertices that are the shortest and not yet determined from Vertex 1                if(!mark[i] && dis[i] < Nextmindis)                    {Nextmindis = dis[i];                    Nextmin = i; Flag =true; }            }//system.out.println ("--------------------------------------");Curmin = Nextmin; } System. out. println ("Shortest path and distance:"); for(inti =0; i < tail; i++) {System. out. Print (Path[i]);if(I! = tail-1) {System. out. Print ("→"); }} System. out. println (); for(inti =0; i < tail; i++) {System. out. Print (Dis[path[i]-1]);if(I! = tail-1) {System. out. Print ("--"); }} System. out. println (); for(inti =0; I < n; i++) {if(!mark[i]) {System. out. println ("Vertex"+ (i+1) +"not reachable"); }        }    } Public Static void Initarray(int[] Dis,intPoint) {//Initialize estimated distance, specify starting distance of 0        //Other unspecified, distance from the vertexDis[point] =0; for(inti =0; i < dis.length; i++) {if(i! = point) {Dis[i] = Arr[point][i];//system.out.println (Dis[i] + "i=" + i);}        }    }}
Results

start at 1Vertex 2 reaches Vertex 3, distanceVertex 2 arrives at Vertex 4, distance 4Vertex 4 arrives at Vertex 3, distance 8Vertex 4 reaches vertex 5, distance fromVertex 4 arrives at vertex 6, distanceVertex 3 reaches vertex 5, distanceVertex 5 reaches vertex 6, distance fromShortest path and distance:1→2→4→3→5→60--1--4--8-- --- -start at 2Vertex 4 arrives at Vertex 3, distance 7Vertex 4 reaches vertex 5, distanceVertex 4 reaches vertex 6, distanceVertex 3 arrives at Vertex 5, distanceVertex 5 reaches vertex 6, distanceShortest path and distance:2→4→3→5→60--3--7-- A-- -Vertex 1 Unreachable
Conclusion

Find the shortest path application still a lot of, do this give me a feeling of doing map navigation. Achievement Max ...

Every time you write Chinese ideas, you can find the thinking loopholes, write code stuck on the back to see ideas, and then write, very good one way.

Of course, this idea can only be understood by oneself (escape

END

Java Practice Dijkstra algorithm to find the shortest path distance

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.