骑士问题
时间限制(普通/Java) : 1000 MS/ 3000 MS 运行内存限制 : 65536 KByte
总提交 : 259 测试通过 : 66
总提交 : 259 测试通过 : 66
比赛描述
国际象棋是一种二人对弈的战略棋盘游戏。国际象棋的棋盘由8×8共64个黑白相间的格子组成,从白棋的角度来看,从左往右为A列至H列,从下往上为第1行至第8行。黑白棋子各16枚,分为王(King)、后(Queen)、车(Rook)、象(Bishop)、马(Knight)、兵(Pawn)六种。其中马(Knight)这种棋子(在西方被成为骑士)的走法与中国象棋中的“马”类似,骑士每一步先横走或直走两格,再向侧面走一格,骑士途经的格子都必须在棋盘以内。
现在给出一枚“骑士”所在的格子以及它要前往的格子的坐标(由一个大写字母和一个数字表示),请你计算出它最少需要走几步。
输入
多组测试数据,每组数据占一行,给出起点和终点的坐标。
输出
每组数据输出一行“From * to * needs at least # steps.”,其中两个‘*’分别代表起点和终点的坐标,‘#’为最少需要的步数,若不超过一步,step后不需要加上s。
样例输入
A1 C2
A1 E3
样例输出
From A1 to C2 needs at least 1 step.
From A1 to E3 needs at least 2 steps.
#include<iostream>
#include<string>
#include<list>
using namespace std;
int distance(int x1, int y1, int x2, int y2){
if(x1==x2 && y1==y2){
return 0;
}
bool map[8][8]={};
int step=0,x,y,levelEndX=x1,levelEndY=y1;
list<int> q;
list<int>::reverse_iterator it;
q.push_back(x1);
q.push_back(y1);
map[x1][y1] = 1;
while(1){
x = q.front();
q.pop_front();
y = q.front();
q.pop_front();
if(x==x2 && y==y2){
return step;
}
if(x-2>=0 && y-1>=0 && map[x-2][y-1]==0){
map[x-2][y-1] = 1;
q.push_back(x-2);
q.push_back(y-1);
}
if(x-2>=0 && y+1<8 && map[x-2][y+1]==0){
map[x-2][y+1] = 1;
q.push_back(x-2);
q.push_back(y+1);
}
if(x-1>=0 && y-2>=0 && map[x-1][y-2]==0){
map[x-1][y-2] = 1;
q.push_back(x-1);
q.push_back(y-2);
}
if(x-1>=0 && y+2<8 && map[x-1][y+2]==0){
map[x-1][y+2] = 1;
q.push_back(x-1);
q.push_back(y+2);
}
if(x+1<8 && y-2>=0 && map[x+1][y-2]==0){
map[x+1][y-2] = 1;
q.push_back(x+1);
q.push_back(y-2);
}
if(x+1<8 && y+2<8 && map[x+1][y+2]==0){
map[x+1][y+2] = 1;
q.push_back(x+1);
q.push_back(y+2);
}
if(x+2<8 && y-1>=0 && map[x+2][y-1]==0){
map[x+2][y-1] = 1;
q.push_back(x+2);
q.push_back(y-1);
}
if(x+2<8 && y+1<8 && map[x+2][y+1]==0){
map[x+2][y+1] = 1;
q.push_back(x+2);
q.push_back(y+1);
}
if(x==levelEndX && y==levelEndY){
it = q.rbegin();
levelEndY = *it;
it++;
levelEndX = *it;
step++;
}
}
}
int main(){
string a, b;
int d;
while(cin>>a>>b){
d = distance(a[0]-'A', a[1]-'1', b[0]-'A', b[1]-'1');
cout<<"From "<<a<<" to "<<b<<" needs at least "<<d<<" step";
if(d<=1){
cout<<"."<<endl;
}else{
cout<<"s."<<endl;
}
}
}