简体   繁体   中英

How do I implement A* in Java?

Here is what I have so far for my pathfinding algorithm:

public void AAlg(int a, int b){
        boolean bool=true;
        while(bool) {
            bool = false;
            for (int i = 0; i <map.length; i++) {
                for (int j = 0; j < map.length; j++) {
                    if(ifObj(i, j)) {
                        bool=true;
                    }
                }
            }
            int smallest=N;
            int[] coords = new int[2];
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if((i==1&&j==0)||(i==2&&j==1)||(i==1&&j==2)||(i==0&&j==1)) {
                        findFGH(i+a,j+b);
                        if(f<smallest) {
                            smallest=f;
                            coords[0]=i+a;
                            coords[1]=j+b;
                        }
                    }
                }
            }
            if(coords[0]==N-1&&coords[1]==.N-1) {
                System.out.println("The distance travelled is "+cnt);
            }
            AAlg(coords[0], coords[1]);
            cnt++;
        }

N is the length of the grid in both width and height, and map is well, the map. It is a boolean[][], with everything false except for where there are obstructions. I envisioned my code to somewhat just from square to square, iterating and finding the most efficient square to go to next. What it wrong? It just loops indefinitely.

This is not an answer to why your algorithm doesn't work but more a helpful source of material you could look at in order to work out how A* works in general. I implemented this algorithm in java a while ago and have recently upgraded it to java13 and put it on github here:

Github repo for A* algorithm project in java13

On top of this is a javafx visual test program where you can play around with the package created from the above module. This is found in the link below:

Git repo of A* visual test app

if you have maven set up to work with github the second project will automatically get the A* package from github i think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM