The method takes as input the coordinates of the starting point and the ending one.
heuristic( int dx , int dy ) { return dx + dy } .
getNeighbors returns adjacent existing and passable nodes.
findMinF returns the node in the list with the lowest value of f .
backtrace finds the route from the last node to the first, converts it into an array with points [x, y].
INode has fields: double f , double g , double h , int x , int y , boolean walkable , boolean opened , boolean closed , INode parent .
public int[][] findPath( int startX, int startY, int endX, int endY) { ArrayList<INode> openList = new ArrayList<INode>(); INode startNode = grid.getNode(startX, startY); double SQRT2 = Math.sqrt(2); INode node, neighbor; INode[] neighbors; int x, y; double ng; startNode.setG(0); startNode.setH( heuristic( Math.abs(startX - endX), Math.abs(startY - endY) ) ); openList.add(startNode); startNode.open(); while ( !openList.isEmpty() ) { node = findMinF( openList ); openList.remove(node); node.close(); if ( node.getX() == endX && node.getY() == endY ) { //Success return Util.backtrace(node); } neighbors = grid.getNeighbors( node.getX(), node.getY() ); for ( int i = 0; i < neighbors.length; i++ ) { neighbor = neighbors[i]; if ( neighbor.isClosed() ) { continue; } x = neighbor.getX(); y = neighbor.getY(); ng = node.getG() + ( ((x - node.getX())&(y - node.getY())) == 0 ? 1.0 : SQRT2); if ( !neighbor.isOpened() || ng < neighbor.getG() ) { neighbor.setG( ng ); neighbor.setH( Weight * heuristic(Math.abs(x - endX), Math.abs(y - endY)) ); neighbor.setParent( node ); } if ( !neighbor.isOpened() ) { openList.add(neighbor); neighbor.open(); } } } //fail System.out.println("fail"); return new int[0][0];} But for any input parameters (with the exception of coincident and neighboring nodes) it indicates the path 6-8 times more than the shortest one, while the values of f reach 500-700, with a card size of 32 * 32 (with an empty map). Maybe somewhere a logic error?
ps And if you don’t add to ng node.getG() , then the algorithm works in direct motion, but the diagonal doesn’t work at all.
findMinFmethodfindMinFit always returned the first node. - Frog