Java implements Dijkstra algorithm to find the shortest path

Source: Internet
Author: User

Task Description: Gets the shortest path description of the starting node to all other nodes in an none graph

The Dijkstra (Dijkstra) algorithm is a typical shortest path routing algorithm used to calculate the shortest path of a node to all other nodes. The main feature is to extend from the center of the starting point to the outer layer until it expands to the end point.

Dijkstra general expressions usually have two ways, a permanent and temporary marking method, one is open, close table
Using the method of Open,close table, it uses the greedy algorithm strategy, the approximate process is as follows:
1. Declare two collections, open and Close,open to store the nodes that are not traversed, and close to store the traversed nodes
2. Initial phase, put the initial node in close, all other nodes into the open
3. Traverse the outer layer at the center of the initial node, get the child node closest to the specified node and place it in close and calculate the new path until close contains all child nodes

The code example is as follows:
The node object is used to encapsulate the nodes ' information, including the name and child nodes

 Public classNode {PrivateString name; PrivateMap<node,integer> child=NewHashmap<node,integer>();  PublicNode (String name) { This. name=name; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicMap<node, integer>Getchild () {returnChild ; }     Public voidSetChild (Map<node, integer>Child ) {         This. Child =Child ; }}

Mapbuilder used to initialize the data source, returning the starting node of the graph

 Public classMapbuilder { PublicNode Build (set<node> Open, set<node>close) {Node NodeA=NewNode ("A"); Node NodeB=NewNode ("B"); Node NodeC=NewNode ("C"); Node noded=NewNode ("D"); Node NodeE=NewNode ("E"); Node Nodef=NewNode ("F"); Node nodeg=NewNode ("G"); Node Nodeh=NewNode ("H"); Nodea.getchild (). Put (NodeB,1); Nodea.getchild (). Put (NodeC,1); Nodea.getchild (). Put (noded,4); Nodea.getchild (). Put (Nodeg,5); Nodea.getchild (). Put (Nodef,2); Nodeb.getchild (). Put (NodeA,1); Nodeb.getchild (). Put (Nodef,2); Nodeb.getchild (). Put (Nodeh,4); Nodec.getchild (). Put (NodeA,1); Nodec.getchild (). Put (Nodeg,3); Noded.getchild (). Put (NodeA,4); Noded.getchild (). Put (NodeE,1); Nodee.getchild (). Put (noded,1); Nodee.getchild (). Put (Nodef,1); Nodef.getchild (). Put (NodeE,1); Nodef.getchild (). Put (NodeB,2); Nodef.getchild (). Put (NodeA,2); Nodeg.getchild (). Put (NodeC,3); Nodeg.getchild (). Put (NodeA,5); Nodeg.getchild (). Put (Nodeh,1); Nodeh.getchild (). Put (NodeB,4); Nodeh.getchild (). Put (Nodeg,1);        Open.add (NodeB);        Open.add (NODEC);        Open.add (noded);        Open.add (NodeE);        Open.add (NODEF);        Open.add (NODEG);        Open.add (Nodeh);        Close.add (NodeA); returnNodeA; }}

The structure of the diagram is as follows:

The Dijkstra object is used to calculate the shortest path from the starting node to all other nodes

 Public classDijkstra {Set<Node> open=NewHashset<node>(); Set<Node> close=NewHashset<node>(); Map<String,Integer> path=NewHashmap<string,integer> ();//Package Path DistanceMap<string,string> pathinfo=NewHashmap<string,string> ();//Package path Information     PublicNode init () {//The initial path, because there is no a->e this path, so path (E) is set to Integer.max_valuePath.put ("B", 1); Pathinfo.put ("B", "A->b"); Path.put ("C", 1); Pathinfo.put ("C", "A->c"); Path.put ("D", 4); Pathinfo.put ("D", "A->d"); Path.put (E, Integer.max_value); Pathinfo.put ("E", "A"); Path.put ("F", 2); Pathinfo.put ("F", "A->f"); Path.put ("G", 5); Pathinfo.put ("G", "A->g"); Path.put (H, Integer.max_value); Pathinfo.put ("H", "A"); //Put the initial node in close and the other nodes into the openNode start=NewMapbuilder (). Build (Open,close); returnstart; }     Public voidComputepath (node start) {node nearest=getshortestpath (start);//take the nearest child node from the start node and put the close        if(nearest==NULL){            return;        } close.add (nearest);        Open.remove (nearest); Map<Node,Integer> childs=Nearest.getchild ();  for(Node child:childs.keySet ()) {if(Open.contains (Child)) {//If the child node is in openInteger Newcompute=path.get (Nearest.getname ()) +Childs.get (child); if(Path.get (Child.getname ()) >newcompute) {//the distance previously set is greater than the newly calculated distancePath.put (Child.getname (), newcompute); Pathinfo.put (Child.getname (), Pathinfo.get (Nearest.getname ())+ "+" +child.getname ()); }}} Computepath (start);//repeat yourself to ensure that all child nodes are traversedComputepath (nearest);//recursively to the outer layer until all vertices are traversed    }     Public voidPrintpathinfo () {Set<map.entry<string, string>> pathinfos=Pathinfo.entryset ();  for(Map.entry<string, string>Pathinfo:pathinfos) {System.out.println (Pathinfo.getkey ()+":"+Pathinfo.getvalue ()); }    }    /*** Get the nearest child node with node*/    PrivateNode Getshortestpath (node node) {Node res=NULL; intmindis=Integer.max_value; Map<Node,Integer> childs=Node.getchild ();  for(Node child:childs.keySet ()) {if(Open.contains (Child)) {intDistance=Childs.get (child); if(distance<Mindis) {Mindis=distance; Res=Child ; }            }        }        returnRes; }}

Main for testing Dijkstra objects

 Public class Main {    publicstaticvoid  main (string[] args) {        Dijkstra test =new  Dijkstra ();        Node start=test.init ();        Test.computepath (start);        Test.printpathinfo ();    }}

Print out the following:
D:a->d
E:a->f->e
F:a->f
G:a->c->g
B:a->b
C:a->c
H:a->b->h

Java implements Dijkstra algorithm to find the shortest path

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.