为了说明A*算法,通过求解一个问题引入
Knight Moves
中国象棋里,马的走法是按照“日”字行走,如下图所示,最多有8个方向可以选择。
这是跳一步可以到达的8个格子。
对问题进行抽象,把每个格子看成一个点的坐标。目标:马从起点x1,y1到x2,y2,怎样走所需的步数最少,路线是怎样的。
每步的跳跃造成的马坐标的变化可能为{{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}}
假设A1的坐标为(0,0)
代码(用STL的优先队列实现的取f值最小的元素)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Astar {
static class Knight{
int x,y;
int step=0;
int f,g,h;
char row; int column;
Knight parent = null;
public Knight(char c, int n){
this.x = c - 'A';
this.y = n - 1;
this.row = c;
this.column = n;
}
public Knight(int x, int y){
this.x = x;
this.y = y;
this.row = (char) (x + (int)'A');
this.column = y + 1;
}
}
static Knight k,end;//k is start point, end is end point
static int sum;
public boolean in(Knight p){
if(p.x<0 || p.y<0 || p.x>=8 || p.y>=8)
return false;
return true;
}
//manhattan估价函数
public static int h(Knight p, Knight end){
return (Math.abs(p.x-end.x)+Math.abs(p.y-end.y))*10;
}
int[][] dir={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
boolean[][] visited = new boolean[8][8];
//以f值为key排序
static Comparator<Knight> OrderComparator = new Comparator<Knight>(){
public int compare(Knight k1, Knight k2){
int f1 = k1.f;
int f2 = k2.f;
if(f1>f2) return 1;
else if(f2>f1) return -1;
else return 0;
}
};
static PriorityQueue<Knight> openSet = new PriorityQueue<Knight>(OrderComparator);
static ArrayList<Knight> closedSet = new ArrayList<Knight>();
public Astar(){
Knight t;
while(!openSet.isEmpty()){
t = openSet.remove();
visited[t.x][t.y] = true;
closedSet.add(t);
if(t.x == end.x && t.y == end.y){
sum = t.step;
end = t;
break;
}
for(int i = 0; i<8;i++){
Knight s = new Knight(t.x + dir[i][0],t.y + dir[i][1]);
if(in(s) && !visited[s.x][s.y]){
s.g = t.g + 23;
s.h = h(s,end);
s.f = s.g + s.h;
s.step = t.step + 1;
s.parent = t;//parent of s is t
openSet.add(s);
}
}
}
}
public static void main(String[] args){
k = new Knight('A', 1);
end = new Knight('A', 2);
k.g = k.step = 0;
k.h = Astar.h(k,end);
k.f = k.g + k.h;
k.parent = null;//start is root, without parent
while(!openSet.isEmpty()) openSet.poll();
openSet.add(k);//start
new Astar();
System.out.println("step is " + sum);
while(end!=null){
System.out.println(end.row+","+end.column+","+end.f);
end = end.parent;
}
}
}