题意描述很烂,完全没考虑不会国际象棋的人的感受。。。
给一个8×8的棋盘,每次给你两个坐标
问从第一个坐标到达第二个坐标的最少步数
棋子是马!!就是中国象棋里的马的走法
e2 e4
横坐标为1-8
纵坐标为a-h
用BFS跑一个就过了,就是题意描述很坑人
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
class coordinate
{
public:
int x,y;
int counter;
};
bool operator==(coordinate a,coordinate b)
{
return a.x==b.x&&a.y==b.y;
}
bool board[9][9];//有效范围1到8
bool inBoard(coordinate a)
{
if(a.x>=1&&a.x<=8&&a.y>=1&&a.y<=8)
{
return true;
}
return false;
}
int main()
{
char input[4];
while(cin>>input[0]>>input[1]>>input[2]>>input[3])
{
memset(board,false,sizeof(board));
coordinate start,goal;
start.x=input[0]-'a'+1;
start.y=input[1]-'1'+1;
start.counter=0;
goal.x=input[2]-'a'+1;
goal.y=input[3]-'1'+1;
queue<coordinate>Q;
Q.push(start);
coordinate temp;
while (!Q.empty())
{
temp=Q.front();Q.pop();
if(temp==goal)
{
break;
}
board[temp.x][temp.y]=true;
for (int i = 0; i < 8; i++)
{
coordinate tt;
tt.x=temp.x+dir[i][0];
tt.y=temp.y+dir[i][1];
tt.counter=temp.counter+1;
if(inBoard(tt)&&board[tt.x][tt.y]==false)
{
Q.push(tt);
}
}
}
printf("To get from %c%c to %c%c takes %d knight moves.\n",input[0],input[1],input[2],input[3],temp.counter);
}
return 0;
}