您的位置:首页 > 其它

Uva 439 Knight Moves

2016-04-05 18:58 295 查看
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

int IsVis[9][9];//记录位置是否被访问
int StaX,StaY,EndX,EndY;
char Start[3],End[3]; //起始及结束位置
typedef struct node
{
int x,y,MoveNum;
}knight;
int Move[8][2]={-1,2, -2,1, 2,1, 1,-2, 1,2, 2,-1, -1,-2, -2,-1};//骑士的移动方位
void Bfs(int x,int y);

int main(){
//freopen("D:\\t.txt","r",stdin);
while(cin>>Start>>End){
StaX = Start[0] - 'a' + 1;
StaY = Start[1] - '0';
EndX = End[0] - 'a' + 1;
EndY = End[1] - '0';//对输入的棋子的位置进行处理
Bfs(StaX,StaY);
}
return 0;
}
void Bfs(int x,int y){
knight m,n;
queue<knight> Que;

m.x = x;
m.y = y;
m.MoveNum = 0;
memset(IsVis,0,sizeof(IsVis));//每一回合棋盘初始化
IsVis[m.x][m.y] = 1;
Que.push(m);
while(!Que.empty()){
m = Que.front();
Que.pop();
if(m.x == EndX&&m.y == EndY){
cout<<"To get from "<<Start[0]<<Start[1]<<" to "<<End<<" takes "<<m.MoveNum<<" knight moves."<<endl;
break;
}//如果到达结束位置,结束
for(int i = 0;i < 8;i++){
if((m.x + Move[i][0] > 0) && (m.x + Move[i][0] < 9) && (m.y + Move[i][1] > 0) && (m.y + Move[i][1] < 9)
&& !IsVis[m.x + Move[i][0]][m.y + Move[i][1]]){//判断移动是否超范围及是否被访问
n.x = m.x + Move[i][0];
n.y = m.y + Move[i][1];
n.MoveNum = m.MoveNum + 1;
Que.push(n);
}
}
}

}


题目说的是骑士从一个位置移动到另一个位置所需的步数,国际象棋里骑士移动和中国象棋里的马类似,都是“日”形。

题目用bfs求解,要运用到队列,使得骑士走的步数不断更新。以便在bfs过程中,统计的移动步数是最短的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: