问题 Z: Knight Moves
时间限制: 1 Sec 内存限制: 128 MB
提交: 23 解决: 22
[提交][状态][讨论版][命题人:quanxing]
题目描述
输入n代表有个n*n的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。
输入
首先输入一个n,表示测试样例的个数。
每个测试样例有三行。
第一行是棋盘的大小L(4≤L≤300);
第二行和第三行分别表示马的起始位置和目标位置(0~L-1)。
输出
马移动的最小步数,起始位置和目标位置相同时输出0。
样例输入
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
样例输出
5
28
0
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n,sx,sy,ex,ey,l,flag,sum1;
int dir[8][2]={1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-1,2,-2,1};
int a[300][300]={0};
struct node
{
int x;
int y;
int sum=0;
}s,e,temp;
int main()
{
cin>>n;
while(n--)
{
flag=0;
queue<node>q;
cin>>l;
cin>>s.x>>s.y>>e.x>>e.y;
memset(a,0,sizeof(a));
q.push(s);
temp=q.front();
while(!q.empty())
{
temp=q.front();
sum1=temp.sum;
q.pop();
if(temp.x==e.x&&temp.y==e.y)
break;
for(int i=0;i<8;i++)
{
temp.x+=dir[i][0];
temp.y+=dir[i][1];
if(!a[temp.x][temp.y]&&temp.x>=0&&temp.x<l&&temp.y>=0&&temp.y<l)
{
a[temp.x][temp.y]=1;
temp.sum=sum1+1;
q.push(temp);
}
temp.x-=dir[i][0];
temp.y-=dir[i][1];
}
}
cout<<temp.sum<<endl;
}
return 0;
}