我对AStar算法的探索
最近读到一篇关于《HTML5实现炮塔防守》的文章,对其中的路径搜索算法有点兴趣,稍微探索了一下。
基于搜索下载的Micheal Hong的Java版本的AStar算法,并做了一些调整。核心代码如下:
while (open.isEmpty() == false) {close.add(open.remove(0));getNeighbour(node, neighbour);for (int i = 0; i < neighbour.length; i++) {if ((index = contain(open, neighbour[i].x, neighbour[i].y)) != -1) {if (open.get(index).gn > neighbour[i].gn)// 以前掠过这个节点的时候(getNeighbour的形式)的代价比现在掠过这里的代价大,说明现在的掠过更好// 所以用现在的掠过代替?也就是说要把原来的那个替换掉,open.set(index, neighbour[i]);// 反之,就不考虑这个新的掠过} elseopen.add(neighbour[i]); // 没有曾经掠过,就作为候选节点加入}/* 判断是否到达目标 */if ((index = contain(open, end.x, end.y)) != -1) {int count = 1;Node d = open.get(index);while (d.father != null) {d = d.father;count++;}d = open.get(index);int[][] path = new int[count][];for (int i = count - 1; i >= 0; i--) {path[i] = new int[2];path[i][0] = d.x;path[i][1] = d.y;d = d.father;}return path;}/* 对open表进行排序(按fn由小到大) */// 我认为可以不用sort,只是取一个值而已,// 也可以在加入open队列的时候就已经形成了大值排序Collections.sort((open));}