题目编号:1015
题目大意:一个8*8的棋盘,骑士只能走日字型,求从给定的起点和终点需要走的最少步数。
解题思路:没什么特别的,就是广搜。创建结构体,内涵行列和步数,用队列来进行存储。先表示出来起点终点的行列坐标,然后广搜即可。
做题感想:看到这个题,我一下子想到老师的例题了,不过有所区别,老师的是给定的棋盘大小,这个是固定的,然后稍微修改就可以了,方法都是一般的广搜,剪枝也大同小 异。
#include<iostream>
#include<queue>
using namespace std;
typedef struct point{
int x,y;
int moves;
}point;
queue<point>Q;
int e_x,e_y;
int map[10][10];
int dir[8][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}};
int i,j,ans,x,y;
point start;
string s;
int bfs(point s)
{
map[s.x][s.y]=1;
point head,t;
Q.push(s);
while(!Q.empty ())
{
head=Q.front();
Q.pop();
if(head.x==e_x&&head.y==e_y)
return head.moves;
for(i=0;i<8;i++)
{
x=head.x+dir[i][0];
y=head.y+dir[i][1];
if(x>=0&&x<8&&y>=0&&y<8&&!map[x][y])
{
map[x][y]=1;
t.x=x;
t.y=y;
t.moves=head.moves+1;
Q.push(t);
}
}
}
}
int main()
{
while(1)
{
cin>>s;
memset(map,0,sizeof(map));
while(!Q.empty())
Q.pop();
start.x=s[0]-'a';
start.y=s[1]-'1';
e_x=s[3]-'a';
e_y=s[4]-'1';
start.moves=0;
ans=bfs(start);
cout<<"To get from "<<s[0]<<s[1]<<" to "<<s[3]<<s[4]<<" takes "<<ans<<" knight moves."<<endl;
}
return 0;
}