站外题
  • 板块学术版
  • 楼主x1489631649
  • 当前回复7
  • 已保存回复7
  • 发布时间2023/11/26 13:35
  • 上次更新2023/11/26 15:43:33
查看原帖
站外题
780505
x1489631649楼主2023/11/26 13:35

求助

题目描述
输入n代表有个n×n的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。

输入格式
数据共有三行。 第一行是棋盘的大小L(4≤L≤300); 第二行和第三行分别表示马的起始位置和目标位置(0..L−1)。

输出格式
马移动的最小步数,起始位置和目标位置相同时输出0。

样例
【输入样例】
8
0 0
7 0
【输出样例】
5
数据范围与提示
4≤L≤300

代码如下

#include <bits/stdc++.h>
using namespace std;
int vis[1000][1000],n,A1,B1,A2,B2;
struct node{
	int x,y;
	int step;
}q[10000];
void bfs()
{
	int t,h;
	t=h=1;
	q[h].x=A1;
	q[h].y=B1;
	q[h].step=0;
	vis[q[h].x][q[h].y]=1;
	while(h<=t)
	{
		int nx1=q[h].x+2,ny1=q[h].y+1;
		int nx2=q[h].x+2,ny2=q[h].y-1;
		int nx3=q[h].x-2,ny3=q[h].y+1;
		int nx4=q[h].x-2,ny4=q[h].y-1;
		int nx5=q[h].x+1,ny5=q[h].y+2;
		int nx6=q[h].x+1,ny6=q[h].y-2;
		int nx7=q[h].x-1,ny7=q[h].y+2;
		int nx8=q[h].x-1,ny8=q[h].y-2;
		if(nx1==A2&&ny1==B2||nx2==A2&&ny2==B2||nx2==A2&&ny2==B2||nx3==A2&&ny3==B2||nx4==A2&&ny4==B2||nx5==A2&&ny5==B2||nx6==A2&&ny6==B2||nx7==A2&&ny7==B2||nx8==A2&&ny8==B2)
		{
			cout<<q[h].step+1;
			return;
		}
		if(nx1<n&&nx1>=0&&ny1<n&&ny1>=0&&vis[nx1][ny1]==0)
		{
			t++;
			q[t].x=nx1;
			q[t].y=ny1;
			q[t].step=q[h].step+1;
			vis[nx1][ny1]=1;
		}
		if(nx2<n&&nx2>=0&&ny2<n&&ny2>=0&&vis[nx2][ny2]==0)
		{
			t++;
			q[t].x=nx2;
			q[t].y=ny2;
			q[t].step=q[h].step+1;
			vis[nx2][ny2]=1;
		}
		if(nx3<n&&nx3>=0&&ny3<n&&ny3>=0&&vis[nx3][ny3]==0)
		{
			t++;
			q[t].x=nx3;
			q[t].y=ny3;
			q[t].step=q[h].step+1;
			vis[nx3][ny3]=1;
		}
		if(nx4<n&&nx4>=0&&ny4<n&&ny4>=0&&vis[nx4][ny4]==0)
		{
			t++;
			q[t].x=nx4;
			q[t].y=ny4;
			q[t].step=q[h].step+1;
			vis[nx4][ny4]=1;
		}
		if(nx5<n&&nx5>=0&&ny5<n&&ny5>=0&&vis[nx5][ny5]==0)
		{
			t++;
			q[t].x=nx5;
			q[t].y=ny5;
			q[t].step=q[h].step+1;
			vis[nx5][ny5]=1;
		}
		if(nx6<n&&nx6>=0&&ny6<n&&ny6>=0&&vis[nx6][ny6]==0)
		{
			t++;
			q[t].x=nx6;
			q[t].y=ny6;
			q[t].step=q[h].step+1;
			vis[nx6][ny6]=1;
		}
		if(nx7<n&&nx7>=0&&ny7<n&&ny7>=0&&vis[nx7][ny7]==0)
		{
			t++;
			q[t].x=nx7;
			q[t].y=ny7;
			q[t].step=q[h].step+1;
			vis[nx7][ny7]=1;
		}
		if(nx8<n&&nx8>=0&&ny8<n&&ny8>=0&&vis[nx8][ny8]==0)
		{
			t++;
			q[t].x=nx8;
			q[t].y=ny8;
			q[t].step=q[h].step+1;
			vis[nx8][ny8]=1;
		}
		h++;
	}
}
int main()
{
//	freopen("1257.in","r",stdin);
//	freopen("1257.out","w",stdout);
	cin>>n;
	cin>>A1>>B1;
	cin>>A2>>B2;
	if(A1==A2&&B1==B2)
	{
		cout<<0;
		return 0;
	}
	bfs();
	return 0;
}
2023/11/26 13:35
加载中...