Dijkstra algorithm of Shortest Path algorithm (Java implementation)

Source: Internet
Author: User

Preface

The Dijkstra algorithm is a familiar one in the shortest path algorithm, and is a single-origin full-path algorithm. This algorithm is known as a successful model of "greedy algorithm". This article will then try to introduce this great algorithm in the most popular language and give Java implementation code.

First, knowledge Preparation:

1, the data structure of the representation diagram

There are many data structures used to store graphs, the adjacency matrix is used in this algorithm.

The adjacency matrix of a graph is stored in two arrays to represent the graph. A one-dimensional array stores the vertex information in a graph, and a two-dimensional array (adjacency matrix) stores information about edges or arcs in the diagram.

Figure G has n vertices, then the adjacency matrix is a n*n square, defined as:

  

As can be seen from the above, the edge array of the non-graph is a symmetric matrix. The so-called symmetric matrix is the element of n-order matrix satisfies AIJ = Aji. That is, from the upper-left corner of the matrix to the lower-right corner of the main diagonal axis, the upper-right corner of the element and the lower-left corner of the corresponding elements are all equal.

From this matrix, it is easy to know the information in the graph.

(1) It is easy to judge whether any two vertices have a boundless edge;

(2) To know the degree of a vertex is actually the sum of the elements of this vertex VI in the first row or (column i) of the adjacency matrix;

(3) Finding all the adjacency points of Vertex VI is to scan the element I of the matrix once, Arc[i][j] 1 is the adjacency point;

and the direction of the map to pay attention to the degree and the degree of the Vertex VI in the degree of 1, just is the sum of the number of the first column I. The dimension of vertex VI is 2, which is the sum of the number of rows I.

The definition of a map is similar, so do not repeat it.

2. Single starting point full path

The so-called single-origin full-path, refers to in a diagram, from a starting point, to all nodes of the shortest path.

3, the basic knowledge of graph theory (readers need to find relevant information on their own)

4. Complementary relaxation conditions

Set scalar d1,d2,...., DN to meet

Dj<=di + AIJ, (i,j) belongs to A,

and P is the path to the end of IK as the starting point of I1, if

dj = di + AIJ, on all sides of P (i, J)

Set, then p is the shortest path from I1 to IK. wherein, satisfies the above two type to be called the shortest path problem the complementary relaxation condition.

 

Second, the idea of arithmetic

1, make G = (v,e) for a weighted without the graph. If there are two adjacent nodes in G, I and J. AIJ (in this and behind are denoted as subscript, note) for node I to node J weights, in this algorithm can be understood as the distance. Each node has a value of Di (the node tag) that represents its distance from the starting point to one of its paths.

2, the algorithm initially has an array of V to store the list of non-access nodes, we are called a candidate list. The selected Node 1 is the starting node. At the beginning, Node 1 d1=0, the other nodes di= Infinity, and V is all nodes.
After the condition is initialized, the iteration algorithm is then started until V is set to stop when it is empty. The specific iteration steps are as follows:

Remove the node di with the lowest D value from the candidate list. (In this case, the data structure of V uses the priority queue to achieve the minimum value of the dequeue, preferably using Fibonacci pairs, in the previous article has been introduced, performance has a significant hint). For each edge that starts with the node, excluding the node to remove V, (i, J) belongs to A, if DJ > di + AIJ (breach of relaxation conditions),

dj = di + AIJ, (if J has been removed from V, indicating that its minimum distance has been calculated, not participating in this calculation)

You can see that the D value of the node is not increasing in the arithmetic engineering.

The specific algorithm is illustrated below

  

Third, Java code implementation

  

 Public classVertexImplementsComparable<vertex>{    /*** Node name (a,b,c,d)*/    PrivateString name; /*** Shortest Path length*/    Private intpath; /*** Whether the node has been checked out (has been processed)*/    Private Booleanismarked;  PublicVertex (String name) { This. Name =name;  This. Path = Integer.max_value;//initially set to infinity         This. setmarked (false); }         PublicVertex (String name,intpath) {         This. Name =name;  This. Path =path;  This. setmarked (false); } @Override Public intcompareTo (Vertex o) {returnO.path > Path?-1:1; }}

 Public classGraph {/** Vertex*/    PrivateList<vertex>Vertexs; /** Side*/    Private int[] edges; /** Vertices not visited*/    PrivateQueue<vertex>unvisited;  PublicGraph (list<vertex> Vertexs,int[] edges) {         This. Vertexs =Vertexs;  This. edges =edges;    Initunvisited (); }        /** Search for each vertex shortest path*/     Public voidsearch () { while(!Unvisited.isempty ()) {Vertex Vertex=unvisited.element (); //The vertex has calculated the shortest path and is set to "accessed"Vertex.setmarked (true); //get all "not visited" NeighborsList<vertex> Neighbors =getneighbors (vertex); //update the shortest path of a neighborupdatesdistance (vertex, neighbors);        Pop (); } System.out.println ("Search Over"); }        /** Update the shortest path for all neighbors*/    Private voidUpdatesdistance (Vertex Vertex, list<vertex>neighbors) {         for(Vertex neighbor:neighbors) {updatedistance (Vertex, neighbor); }    }        /** Update the shortest path of a neighbor*/    Private voidupdatedistance (Vertex Vertex, Vertex neighbor) {intDistance = getdistance (vertex, neighbor) +Vertex.getpath (); if(Distance <Neighbor.getpath ())        {Neighbor.setpath (distance); }    }    /** Initialize an unreachable vertex collection*/    Private voidinitunvisited () {unvisited=NewPriorityqueue<vertex>();  for(Vertex v:vertexs) {unvisited.add (v); }    }    /** Delete the node that has found the shortest path from the never accessed vertex collection*/    Private voidpop () {unvisited.poll (); }    /** Gets the distance from the vertex to the target vertex*/    Private intgetdistance (Vertex source, Vertex destination) {intSourceIndex =vertexs.indexof (source); intDestindex =vertexs.indexof (destination); returnEdges[sourceindex][destindex]; }    /** Get vertex all (not visited) neighbors*/    PrivateList<vertex>getneighbors (Vertex v) {List<Vertex> Neighbors =NewArraylist<vertex>(); intPosition =Vertexs.indexof (v); Vertex Neighbor=NULL; intdistance;  for(inti = 0; I < vertexs.size (); i++) {            if(i = =position) {                //vertex itself, skipping over                Continue; } Distance= Edges[position][i];//distance to all vertices            if(Distance <integer.max_value) {                //is a neighbor (with path to reach)Neighbor =Getvertex (i); if(!neighbor.ismarked ()) {                    //if the neighbor has not visited, then join the list;Neighbors.add (neighbor); }            }        }        returnNeighbors; }    /** Get vertices based on vertex position*/    PrivateVertex Getvertex (intindex) {        returnVertexs.get (index); }    /** Print Diagram*/     Public voidprintgraph () {intVernums =vertexs.size ();  for(introw = 0; Row < Vernums; row++) {             for(intcol = 0; Col < Vernums; col++) {                if(Integer.max_value = =Edges[row][col]) {System.out.print (X); System.out.print (" "); Continue;                } System.out.print (Edges[row][col]); System.out.print (" ");        } System.out.println (); }    }}

    

 Public classTest { Public Static voidMain (string[] args) {List<Vertex> Vertexs =NewArraylist<vertex>(); Vertex a=NewVertex ("A", 0); Vertex b=NewVertex ("B"); Vertex C=NewVertex ("C"); Vertex D=NewVertex ("D"); Vertex e=NewVertex ("E"); Vertex F=NewVertex ("F");        Vertexs.add (a);        Vertexs.add (b);        Vertexs.add (c);        Vertexs.add (d);        Vertexs.add (e);        Vertexs.add (f); int[] edges ={{integer.max_value,6,3, Integer.max_value,integer.max_value,integer.max_value}, {6,integer.max_value,2,5, Integer.max_value,integer.max_value}, {3,2,integer.max_value,3,4, Integer.max_value}, {integer.max_value,5,3,integer.max_value,5,3}, {integer.max_value,integer.max_value,4,5,integer.max_value,5}, {integer.max_value,integer.max_value,integer.max_value,3,5, Integer.max_value}}; Graph Graph=NewGraph (Vertexs, edges);        Graph.printgraph ();    Graph.search (); }    }

Four, recommended Reading

Ford-fulkerson algorithm of maximal flow problem in network

 

Dijkstra algorithm of Shortest Path algorithm (Java implementation)

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.