A * algorithm to find the shortest Path Java source code (can be used)

Source: Internet
Author: User

accidentally see the shortest short-circuit strength problem, in the game, navigation and other fields have been applied, it is very interesting, it is intended to achieve a version of their own. Finally, an efficient and concise * algorithm is selected.

A * is really a very good implementation, compared to Digetsla, Best-first and other algorithms, here to save 10,000 words of praise ...

A * algorithm company can read this article:

http://blog.csdn.net/pi9nc/article/details/8779503

The implementation of a * is not complex, the key 1th: Judging the current after each step, the next step, the general use of an open set and a closed set to store the next to go to the lattice and have already traversed the lattice; 2nd: How to determine which grid to go next, which is also a * of excellence, It takes into account the distance traveled (cost) and the expected distance (expectation), has a fast and efficient way to find the road, here again omit 10,000 words of praise ...

This article is slightly improved by using the smallest heap to store the next possible lattice, and using the inverted tree (the tree that points to the pointer to the parent node in the node, let me say so) to record the road strength.

Minimum heap See: http://blog.csdn.net/abcd_d_/article/details/40379125

Total four categories:

1, Mycompare.java is an interface

2, Minheap.java Generic Minimum heap, the implementation of reference to the Java API ArrayList, code re-usable

3, Grid.java lattice class, used to record lattice information and simple operation

4. Astar.java* Algorithm main logic class


On the code:

Package com.study.algorithm;/** * Compare size function interface * @author Zhangshaoliang * 2015-5-7 pm 12:28:12 */public interface Mycompare {PU Blic boolean Islarger (mycompare m2);p ublic boolean issmaller (mycompare m2);p ublic boolean isequal (Mycompare m2);}
Package com.study.algorithm;/** * Pojo, lattice * <pre> F = g + H * G means the movement cost of moving from start a to the specified square on the grid (can be moved in the oblique direction, the cost of the oblique direction is the diagonal length) * H Represents the estimated cost of moving from the specified square to the end B (H has many calculations, here we set can only move up and down) .</pre> * @author Zhangshaoliang * 2015-5-7 pm 1:00:09 */public clas s Grid implements mycompare{private double F;private double h;private double g;private int i;p rivate int j;private Grid p arent; The lattice's parent lattice/** * Pojo, Lattice * @param f f = g + H * @param g represents the movement cost of moving from start a to the specified square on the grid (can be moved in the oblique direction, the cost of the oblique direction is the diagonal length) * @param H indicates from the specified square The estimated cost of moving to end B (H has a lot of calculation methods, here we can only move up and down around). * @param i ordinate i * @param J Horizontal Axis J * @param parent node */public Grid (double f,double g,double h,int i,int j,grid parent) {thi S.F = F;this. G = G;this. H = h;this.i = I;THIS.J = J;this.parent = parent;} Public Grid () {}public grid getParent () {return parent;} public void SetParent (Grid parent) {this.parent = parent;} public int Geti () {return i;} public int Getj () {return J;} public void SetI (int i) {this.i = i;} public void Setj (int j) {this.j = j;} /** * Total cost through the current point to the end of B Expected * @return */public double getf () {return F;} /** * H represents the estimated cost of moving from the specified square to the end B (H has many calculations, where we can only move up or down) * @return */public double Geth () {return H;} /** * Indicates the movement cost from start A to the current grid (can be moved in the oblique direction, the cost of the oblique direction is the diagonal length) * @return */public double Getg () {return G;} public void setf (double f) {f = f;} public void SetH (double h) {h = h;} public void Setg (double g) {g = g;} @Overridepublic boolean Islarger (mycompare m2) {//TODO auto-generated method Stubreturn this. F> (Grid) m2). GETF ();} @Overridepublic boolean Issmaller (mycompare m2) {//TODO auto-generated method Stubreturn this. f< (Grid) m2). GETF ();} @Overridepublic boolean isequal (mycompare m2) {//TODO auto-generated method Stubreturn this. f== (Grid) m2). GETF ();}}

Package com.study.algorithm;/** * Minimum heap * @author Zhangshaoliang * 2015-5-7 a.m. 11:08:20 */public class Minheap<e extends My compare> {private int size;private object[] element;public minheap (int maxSize) {size = 0;element = new Object[maxsize]; }public Minheap () {this (10);} /** * element into heap * @param e */public void append (e e) {ensurecapacity (size+1); element[size++] = E;///put The element to the end O f the Heapadjustup (); Adjust the heap to minheap}/** * Remove heap top element (minimum element) * @return */@SuppressWarnings ("unchecked") public E poll () {if (IsEmpty ()) {R Eturn null;} E min = (e) element[0];element[0] = element[size-1];///replace the min element with the last element element[size-1] = nul l;///let GC do it Worksize--;adjustdown ();///adjust the heap to Minheapreturn min;} /** * View heap top element (minimum element) * @return */@SuppressWarnings ("unchecked") public E Peek () {if (IsEmpty ()) {return null;} Return (E) element[0];} /** * is empty heap * @return */public boolean isEmpty () {return size = = 0;} /** * Ensure sufficient capacity space * @param mincapacity */private voID ensurecapacity (int mincapacity) {int oldcapacity = element.length;if (mincapacity > oldcapacity) {int newCapacity = ( OLDCAPACITY*3)/2+1;///up to 1.5 times times per object[] copy = new object[newcapacity];///Call the local C method for array replication system.arraycopy (element, 0, Copy, 0, element.length); element = copy;}} /** * Upward adjustment to the heap, the small value upward */@SuppressWarnings ("unchecked") private void Adjustup () {e temp = (e) element[size-1];///get the last  element int parent = Size-1;while (parent>0&& ((E) element[(size-1)/2]). Islarger (temp)) {///if smaller than it Parentelement[parent] = element[(parent-1)/2];p arent = (parent-1)/2;} Element[parent] = temp;} /** * Downward adjustment to heap */@SuppressWarnings ("unchecked") private void Adjustdown () {E temp = (E) element[0];///get the first element i NT child = 1;while (child<size) {e left = (e) element[child]; e right = (e) element[child+1];///here the child+1 does not cross the border (think about why) if (Right!=null&&left.islarger (right)) {child++;} if ( Temp.issmaller ((E) Element[child]) {break;////if smaller than two children, end}element[(child-1)/2] = Element[child]; Assign the smaller to its parentchild = child*2 + 1;} element[(CHILD-1)/2] = temp;}}

Package com.study.algorithm;/** * * * * pathfinding algorithm * <pre> * idea: Take the lowest expected position each time as the next step to go, F = g + H * g means moving from start A to a specified square on the grid (can be moved in oblique direction, the cost of oblique direction is the diagonal length). * H indicates the estimated cost of moving from the specified square to the end B (H has a lot of calculations, here we can only move up or down). * * Here a minimum heap is used to record the grid in the open list, and each grid has a pointer to the parent lattice, which records the road strength </pre> * @author Zhangshaoliang * 2015-5-7 a.m. 10:58:54 */public Clas s AStar {private static minheap<grid> open;//= new minheap<grid> ();//private static MTree close;//= new Mtre E ();p rivate Grid last; Record last lattice private final String obstacle = "1";//obstacle Tag Value private string end = "E";////target Tag Value private string start = "S";////start label Value//target coordinate private int end_i =-1; private int end_j = -1;//start target private int start_i = -1;private int start_j = -1;/** * Initialize operation * @param boxs */public void INI T (string[][] boxs) {for (int. i=0;i<boxs.length;i++) {for (int j=0;j<boxs[0].length;j++) {if (Boxs[i][j].equals ( Start)) {start_i = I;start_j = j;} if (boxs[i][j].equals (end)) {end_i = I;end_j = J;}}} Grid Sgrid = new Grid (0, 0, 0, start_i, start_j, null); open = new minheap<grid> (); Open.append (Sgrid);/////Start position join open set}/** * Start search */public void Search (string[][] boxs) {int Height = boxs.length;int width = boxs[0].length;while (Open.peek ()!=null) {//folio is traversed until the target is found or the path grid G = Open.poll () is missing; int i = G.geti (), Int j = G.GETJ ();d ouble pre_g = G.GETG ();///Consumed for (int. h=-1;h<=1;h++) {for (int w=-1;w<=1;w++) {int NE Xt_i = i + h;///Next will join the open set of the lattice iint Next_j = j + w;///Next will join the open set of the lattice Jif (next_i>=0 && next_i<=height-1 &am p;& next_j>=0 && next_j<=width-1) {////array does not range, then computes if (boxs[next_i][next_j].equals (obstacle) | | boxs [Next_i] [Next_j].equals ("-1") | | (h==0&&w==0)) {//If the lattice is a barrier, or the lattice itself, skips continue;} Calculates the shortest short-circuit strength of the point to the endpoint double H = Math.Abs (end_i-next_i) + Math.Abs (End_j-next_j), if (h<1) {///finds the target, records and ends last = new Grid (0 , Pre_g, 0, Next_i, next_j,g); return;} If it is diagonal then add 1.4, otherwise add 1double G = math.sqrt ((next_i-i) * (next_i-i) + (next_j-j) * (next_j-j)) >1? pre_g+1.4:pre_g+1;//Generate new grid Grid temp = new Grid (H+g, G, H, next_i, NEXT_J,G);////joins open set Open.append (temp); Boxs[i][j] = "1";///indicates that}}}last = G has been calculated here;}} /** * Print path strength */public void Printpath () {if (End_i!=last.geti () | | END_J!=LAST.GETJ ()) {System.out.println ("Cannot reach the end! "); return;} System.out.println ("Road in reverse order:"); while (true) {System.out.print ("(" +last.geti () + "," +LAST.GETJ () + ")"); Last.getparent (); if (last==null) {break;} System.out.print ("< ———");}} /** * @param args */public static void main (string[] args) {//TODO auto-generated method Stub/*grid g1 = new Grid (2, 1, 2 , 0, 0,null); Grid g2 = new Grid (5, 1, 2, 0, 0,G1); Grid g3 = new Grid (1, 1, 2, 0, 0,G1); Grid G4 = new Grid (6, 1, 2, 0, 0,G2); Grid g5 = new Grid (3, 1, 2, 0, 0,g3); open = new minheap<grid> (); Open.append (G1); Open.append (G2); Open.append (G3); ope N.append (G4); Open.append (G5);//, Test minimum heap while (Null!=open.peek ()) {System.out.println (Open.poll (). GETF ());} */string[][] Boxs = {//{"0", "G"},{"s", "0"}}; {"0", "0", "1", "0", "0"},{"0", "0", "1", "E", "0"},{"0", "0", "1", "1", "0"},{"0", "0", "0", "1", "0"},{"s", "0", "1", "0", "0"}, };asTar star = new AStar (); Star.init (boxs); Star.search (boxs); Star.printpath ();}} 

Output Result:

<span style= "FONT-SIZE:18PX;" > Road in reverse Order: (1,3) < ——— (2,4) < ——— (3,4) < ——— (4,3) < ——— (3,2) < ——— (3,1) < ——— (4,0) </span>








A * algorithm to find the shortest Path Java source code (can be used)

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.