ZSTU-2331:Knight Moves

//BFS
#include<iostream>
#include<cstring>
#define MAXN 100000
#define N 305
using namespace std;
int mp[N][N];
int dir[8][2] = {{-2,1},{-1,2},{1,-2},{2,1},{2,-1},{1,2},{-1,-2},{-2,-1}};//马走的方向
typedef struct Que
{
	int i,j;
	int step;
}Queue;
Queue q[MAXN];
int front,rear,L,cnt;
int flag;
void BFS(int si,int sj,int ei,int ej)
{
	memset(mp,0,sizeof(mp));
	int i,j,di;
	front =  -1;
	rear = 0;
	q[rear].i = si,q[rear].j = sj;
	q[rear].step = 0;
	while(front<rear)	//如果用循环队列这里就改为front!=rear
	{
//		front = (front+1)%MAXN;//可以用循环队列,数组也不用开那么大10000就够了
		front++;
		i = q[front].i,j = q[front].j;
		if (i==ei && j==ej)
			return;
		di = -1;
		while(++di<8)
		{
			if (i+dir[di][0]>=0&&i+dir[di][0]<L 
				&&j+dir[di][1]>=0 && j+dir[di][1]<L 
				&& mp[i+dir[di][0]][j+dir[di][1]]==0)	//判断是否可走
			{
			//	rear = (rear+1)%MAXN;
				rear++;
				q[rear].i = i+dir[di][0];
				q[rear].j = j+dir[di][1];
				mp[q[rear].i][q[rear].j] = 1;
				q[rear].step = q[front].step+1;//记录步长
			}
		}
	}
}
int main()
{
	int t,si,sj,ei,ej;
	cin>>t;
	while(t--)
	{
		cin>>L>>si>>sj>>ei>>ej;
		if (si==ei &&sj==ej)
			cout<<0<<endl;
		else 
		{
			BFS(si,sj,ei,ej);
			cout<<q[front].step<<endl;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值