The shortest path and length of a weighted graph with a direction without ring

Source: Internet
Author: User
Tags in degrees

Given a topological sequence of a forward-free graph, the shortest path of the sequence from the starting point to the last point of the sequence is obtained.

The starting point defaults to 0 points (vertices are 0,1,2 ...). and array indexes), sequences are obtained by topological ordering.

The following is the implementation, first of all, a forward-loop diagram of the topological ordering class.

 PackageGraphics.dag.topologicalsort;/*** Get a topological sequence *@authorZhangxinren **/ Public classTopologicalsort {//the penetration of each side    Private Static int[] indegree;//adjacency Table element changes, Indegree Initial length also varies//edges currently available for walking (0-in-a-level)    Private StaticLinkednode Next;  Public Static int[] Topologicalsort (int[] edges) {        intm = 0; int[] result =New int[Edges.length]; Indegree=New int[Edges.length];  for(inti = 0; i < indegree.length; i++) {Indegree[i]= 0; }         for(inti = 0; i < edges.length; i++) {             for(intj = 0; J < Edges[i].length; J + +) {Indegree[edges[i][j]]++; }        }         for(inti = 0; i < indegree.length; i++) {            if(Indegree[i] = = 0) {                if(Next = =NULL) {Next=NewLinkednode (i); }                Else{Linkednode Tempnode=NewLinkednode (i); Tempnode.next=Next.next; Next.next=Tempnode; }            }        }                         while(Next! =NULL) {//end when no vertex is zero in degreeLinkednode temp = Next.next;//Take out a vertex with a zero-in degree            if(Temp! =NULL) {Next.next=Temp.next; }            Else{Temp=Next; Next=NULL; } result[m++] =Temp.number; int[] Tempdegree =Edges[temp.number];  for(inti = 0; i < tempdegree.length; i++) {//update points for vertex-in and 0-in degreesindegree[tempdegree[i]]--; if(Indegree[tempdegree[i]] = = 0) {Linkednode Tempnode=NewLinkednode (Tempdegree[i]); if(NULL!=next) {Tempnode.next=Next.next; Next.next=Tempnode; }                    Else{Next=Tempnode; }                }            }        }                returnresult; }}

Auxiliary linked List class

 Package Graphics.dag.topologicalsort;  Public class Linkednode {    int number ;    Linkednode Next;      Public Linkednode (int number ) {        Super();         this. Number = number ;    }}

Plus a class to get the shortest path and shortest path length, the shortest path length and shortest path of the starting point 0 to each vertex in the class can be obtained, and the reader can modify the starting point to obtain the shortest path from different starting point to other points.

 PackageGraphics.dag.topologicalsort;/*** The shortest path of a weighted graph with no loop *@authorZhangxinren **/ Public classShortestpathlength {//an array of shortest paths to vertices    Private Static int[] shortest; //The previous node to the shortest point in the current node path    Private Static int[] pred; //Vertex adjacency Table    Private Static int[] edges = {            {1,2,3},{4},{4,5},{5},{6},{6},{}    }; //adjacency matrix of Edge weights    Private Static int[] Weight ={{integer.max_value,1, 5, 6, Integer.max_value, Integer.max_value, Integer.max_value}, {integer.max_value, Integer.max_value, Integer. Max_value, Integer.max_value,7, Integer.max_value, Integer.max_value}, {integer.max_value, Integer.max_value, Integer.max_value, Integer. Max_value,2, 5, Integer.max_value}, {integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer. Max_value,8, Integer.max_value}, {integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer. Max_value, Integer.max_value,4}, {integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer. Max_value,3}, {integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer.max_value, Integer.        Max_value, Integer.max_value}};  Public Static intShortestpathlength (int[] edges,int[] weight) {        intn =edges.length; Shortest=New int[n]; Pred=New int[n]; //initialization: It is assumed that the shortest path except the starting 0 is 0 and the other is infinite, the previous vertex of the shortest path of the current vertex is None ( -1)         for(inti = 0; I < n; i++) {Shortest[i]=Integer.max_value; Pred[i]=-1; } shortest[0] = 0; //get a sequence of topologies        int[] sequence =topologicalsort.topologicalsort (edges); //process each vertex in a topological sequence         for(inti = 0; i < sequence.length; i++){            inttemp =Sequence[i]; //gets the vertex of the current vertex that is out of the edge            int[] Tempdegree =Edges[temp]; //update the shortest distance for these vertices             for(intj = 0; J < Tempdegree.length; J + +){                intEnd =Tempdegree[j];            Relax (temp, end); }        }                returnShortest[sequence[sequence.length-1]]; }        /*** Start vertex to its next vertex end to see if you need to update shortest[end] * Update the shortest distance when the shortest distance to the start vertex plus the distance between start and end is less than the shortest distance from the end vertex *@paramStart *@paramEnd *@return     */     Public Static BooleanRelaxintStartintend) {        if(Shortest[start]! = Integer.max_value && shortest[end] > Shortest[start] +Weight[start][end]) {Shortest[end]= Shortest[start] +Weight[start][end]; Pred[end]=start; return true; }                return false; }         Public Static voidMain (string[] args) {//Get Shortest path length        intresult =shortestpathlength (edges, weight); int[] sequence =topologicalsort.topologicalsort (edges); System.out.print ("Sequence:");  for(inti = 0; i < sequence.length; i++) {System.out.print (Sequence[i]+ " ");        } System.out.println (); intEnd = Sequence[sequence.length-1]; System.out.println ("Result:" +result); StringBuilder SB=NewStringBuilder (end + ""); intPre =Pred[end];  while(Pre! =-1) {sb.append (pre+ " "); Pre=Pred[pre]; } sb.setlength (Sb.length ()+ W);                Sb.reverse (); //Print the shortest pathSystem.out.println (sb.tostring ()); //print out the shortest path length to all pointsSYSTEM.OUT.PRINTLN ("Shortest path starting from 0");  for(inti = 0; i < edges.length; i++) {System.out.println (i+ ": " +Shortest[i]); }    }}

The following is attached to the non-ring with the right map

The basic algorithm is derived from the algorithm foundation-open the door of the algorithm, according to the description of the book and I understand processing in code form to achieve. The ability to understand is limited, if you do not understand, you can view the relevant information or find books to see for themselves.

The results of the final printing are as follows:

Sequence:0 3 2 5 1 4 6a 2 4 6 Shortest path starting from 0 0:01:12:53:64:75:106:11

The shortest path and length of a weighted graph with a direction without ring

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.