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过程中,统计的移动步数是最短的。
相关文章推荐
- UVa 10452 - Marcus
- UVa144 Student Grants
- Poj 2051 Argus
- POJ 2062 Card Game Cheater
- Uva 10336 Rank the Languages
- 找不到visual studio模板信息 解决方法
- 26.Remove Duplicates from Sorted Array
- 第四周 项目5(3)
- Serializable 和 Parcelable 区别
- Go语言核心之美 4.2-递归函数
- 【FFMPEG】各种音视频编解码学习详解 h264 ,mpeg4 ,aac 等所有音视频格式
- Hadoop学习第一次复习
- 菜鸟学习之smartupload+servlet简单的文件上传
- Tsinsen A1124 进制转换
- Scripts after the Linux server installation
- Activity之间使用intent传递大量数据带来问题总结
- imx6 板卡移植官方yocto版本(2_定制系统)
- linux文件系统介绍
- 构建之法:第四章读后感
- 求长方柱的体积和表面积