原题:
Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov.
For people not familiar with chess, the possible knight moves are shown in Figure 1.
题意:
依然是移动象棋的马走日问题,问从一个点到另一个点最少需要多少步骤。
题解:
可以是说是跟前边两个基本类似,区别就是在于因为要找最少的步骤,所以需要用广搜来搜索,创建队列不断出队然后查找然后队,同时检查要查找的点是否访问过以及是否超出边界,别的就是基本的广搜了。
代码:AC
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef struct
{
int x,y;
int step;
}node;
int visit[1000][1000];
int fx[]={-2,-2,-1,-1,2,2,1,1};
int fy[]={-1,1,-2,2,-1,1,-2,2};
int l;
queue<node>Q;
node start,end;
int check(int i,int j)
{
if(i>=0&&j>=0&&i<l&&j<l&&visit[i][j]==0)
return 1;
return 0;
}
int bfs()
{
start.step=0;
Q.push(start);
visit[start.x][start.y]=1;
node a,next;
while(!Q.empty())
{
a=Q.front();
Q.pop();
int i;
for(i=0;i<8;i++)
{
next.x=a.x+fx[i];
next.y=a.y+fy[i];
if(check(next.x,next.y))
{
next.step=a.step+1;
if(next.x==end.x&&next.y==end.y)
return next.step;
Q.push(next);
visit[next.x][next.y]=1;
}
}
}
return -1;
}
int main()
{
int t,i,j;
cin>>t;
while(t--)
{
cin>>l;
for(i=0;i<l;i++)
for(j=0;j<l;j++)
visit[i][j]=0;
cin>>start.x>>start.y;
cin>>end.x>>end.y;
if(start.x==end.x&&start.y==end.y)
{
cout<<"0"<<endl;
continue;
}
else
{
while(!Q.empty())
Q.pop();
cout<<bfs()<<endl;
}
}
return 0;
}