题意:给你一个8*8的国际象棋棋盘,然后在给你两个初末位置,问你按骑士的走法,最少几步内能从初位置走到末位置。
分析:简单的一个搜索题,为了练a*算法找来水一水。估价函数用曼哈顿距离就行了。
代码如下;
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-8;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const int M=20010;
const int N=10010;
const int d[][2] = { {-1,-2}, {1,-2}, {2,1}, {2,-1}, {-1,2}, {1,2}, {-2,1}, {-2,-1} };
typedef pair<int, int> pii;
int xe,ye,xs,ys;
bool vis[10][10];
char g[10][10];
struct node
{
int g,h,f,x,y,cnt;
node(){ g=h=f=cnt=0; }
bool operator<(const node &t) const
{
return f==t.f?g>t.g:f>t.f;
}
};
int get_h(int x,int y)
{
return (abs(x-xe)+abs(y-ye));
}
int a_star(int xs,int ys)
{
int i,j;
MS(vis,false);
node t;
t.x=xs; t.y=ys;
priority_queue<node>q;
q.push(t);
vis[xs][ys]=true;
while(!q.empty())
{
t=q.top(); q.pop();
int x=t.x,y=t.y;
if (x==xe && y==ye) return t.cnt;
for (i=0;i<8;i++) {
int xx=x+d[i][0], yy=y+d[i][1];
if (xx>=0 && xx<8 && yy>=0 && yy<8 && !vis[xx][yy]){
vis[xx][yy]=true;
node r;
r.g=t.g+23; // 从某个点出发,到达任何另外一个点的距离都是根号5,这里取根号5的10倍取整。
r.h=get_h(xx,yy);
r.f=r.g+r.h;
r.cnt=t.cnt+1;
r.x=xx; r.y=yy;
q.push(r);
}
}
}
return -1;
}
int main()
{
int i,j;
char s1[N],s2[N];
while(~scanf("%s %s",s1,s2))
{
xs=s1[0]-'a'; ys=s1[1]-'1';
xe=s2[0]-'a'; ye=s2[1]-'1';
int t=a_star(xs,ys);
printf("To get from %s to %s takes %d knight moves.\n",s1,s2,t);
}
}