题意分析
在国际象棋棋盘中给出两个点,问马从一个点到另一个点最少需要跳几步。
国际象棋中的马和中国象棋的马没有什么区别,只是没有蹩马腿这一说。
然后就是裸地BFS了。
代码总览
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int nmax = 10;
const int ntx[] = {1,1,-1,-1,2,2,-2,-2};
const int nty[] = {2,-2,2,-2,1,-1,1,-1};
int sx,sy,ex,ey;
bool visit[nmax][nmax];
char sta[nmax],ed[nmax];
void cope(){
sx = sta[0] - 'a';
sy = sta[1] - '1';
ex = ed[0] - 'a';
ey = ed[1] - '1';
}
bool legal(int x ,int y){
if(x <0 || x >= 8 || y<0 || y>=8) return false;
else return true;
}
int bfs(){
queue<int> q;
int x = sx, y = sy , step = 0;
q.push(x);q.push(y);q.push(step);
while(!q.empty()){
x = q.front();q.pop();
y = q.front();q.pop();
step = q.front();q.pop();
visit[x][y]= true;
if(x == ex && y == ey) return step;
for(int i = 0;i<8;++i){
int xx = x + ntx[i];
int yy = y + nty[i];
if(legal(xx,yy) && !visit[xx][yy]){
q.push(xx);q.push(yy);q.push(step+1);
}
}
}
return -1;
}
int main(){
while(scanf("%s",sta) != EOF){
scanf("%s",ed);
memset(visit,0,sizeof visit);
cope();
int ans = bfs();
printf("To get from %s to %s takes %d knight moves.\n",sta,ed,ans);
}
return 0;
}