A*算法是一种有预判优化的搜索根据两个参数g和h和优先队列,选择比较好的下一步。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
using namespace std;
struct node{
int x,y,step,g,h,f;
bool operator < (const node & k) const{
return f > k.f;
}
};
bool v[11][11];
int mx[] = {1,1,-1,-1,2,2,-2,-2};
int my[] = {2,-2,2,-2,1,-1,1,-1};
bool in(int x,int y){
if(x >= 1 && x <= 8 && y >= 1 && y <= 8)
return true;
else
return false;
}
int hdis(node a,node b){
return (abs(a.x - b.x) + abs(a.y - b.y))*10;
}
priority_queue<node> q;
int Astar(node s,node e){
while(!q.empty())
q.pop();
memset(v,0,sizeof(v));
v[s.x][s.y] = 1;
s.step = 0;
s.f = s.g = 0;
s.h = hdis(s,e);
q.push(s);
while(!q.empty()){
node temp = q.top();
q.pop();
if(temp.x == e.x && temp.y == e.y){
return temp.step;
}
for(int i = 0 ; i < 8 ; i ++){
node nt = temp;
nt.x += mx[i];
nt.y += my[i];
if(in(nt.x,nt.y) && v[nt.x][nt.y] == 0){
v[nt.x][nt.y] = 1;
nt.step++;
nt.g += 23;
nt.h = hdis(nt,e);
nt.f = nt.g + nt.h;
q.push(nt);
}
}
}
}
char s[3];
char e[3];
int main(){
while(scanf("%s%s",&s,&e) != EOF){
node src,des;
src.x = int(s[0] - 'a' + 1);
src.y = int(s[1] - '0');
des.x = int(e[0] - 'a' + 1);
des.y = int(e[1] - '0');
printf("To get from %s to %s takes %d knight moves.\n",s,e,Astar(src,des));
}
return 0;
}