Description
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.
Input
The input begins with the number n of scenarios on a single line by itself.
Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 <= l <= 300). The entire board has size l * l. The second and third line contain pair of integers {0, …, l-1}*{0, …, l-1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario.
Output
For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,distance is zero. The distance must be written on a single line.
Sample Input
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
Sample Output
5
28
0
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int INF=100000000 ;//用const int 而不是define
typedef pair<int,int> P;
#define MAX_N 305
int maze[MAX_N][MAX_N];
int L;//行数 列数
int sx,sy;//开始坐标
int gx,gy;//结束坐标
int dx[8]={1,2,-1,-2,-2,-1,1,2},dy[8]={-2,-1,-2,-1,1,2,2,1};
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>L;
queue<P> que;
for(int i = 0;i<L;i++)
{
for(int j = 0;j<L;j++)
{
maze[i][j] = INF;
}
}
//将起点加入队列,并把这一地点的距离设置为0
cin>>sx>>sy;
cin>>gx>>gy;
que.push(P(sx,sy));
maze[sx][sy] = 0;
//不断循环知道队列长度为空
while(que.size())
{
P p=que.front();
que.pop();
if(p.first == gx&&p.second == gy) break;
//八个方向进行循环
for(int i=0;i<8;i++)
{
int nx = p.first+dx[i],ny = p.second+dy[i];
//判断是否越界,以及是否已经访问过(maze[nx][ny]!=INF为已经访问过)
if(nx>=0&&nx<L&&ny>=0&&ny<L&&maze[nx][ny]== INF)
{
//可以移动的话,加入到队列中,并且该为位置的距离确定为到p的距离加一
que.push(P(nx,ny));//注意pair的用法
maze[nx][ny] = maze[p.first][p.second]+1;
}
}
}
cout<<maze[gx][gy]<<endl;
}
return 0;
}