问题 K: 2.4.3 骑士移动

写程序,计算象棋中马从一个位置移动到另一个位置所需的最少移动次数

输入格式
有多组测试数据。
第一行一个整数 T,代表数据组数。
每组数据包含三行。
第一行表示棋盘的长度 L,棋盘大小为 L×L。
第二行包含两个整数 x, y,表示马的起始位置坐标。
第三行包含两个整数 a, b,表示马的终点位置坐标。
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
马走日!!!

BFS 广度优先

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
struct posi
{
	int x;
	int y;
	posi(int x1, int y1)
	{
		x = x1;
		y = y1;
	}
};
int dis[301][301],backup1[301][301];
bool visted[301][301],backup2[301][301];
int xl[8] = { -2,-1,1,2,2,1,-1,-2 };
int yl[8] = { 1,2,2,1,-1,-2,-2,-1 };
int check_boundary(int sizes,posi temp)
{
	if (temp.x >= 0 && temp.x < sizes && temp.y >= 0 && temp.y < sizes)
		return 1;
	return 0;
}
int main()
{
	int times;
	cin >> times;
	int x, y, a, b;
	while (times--)
	{
		int sizes;
		cin >> sizes;
		memcpy(dis, backup1, sizeof backup1);
		memcpy(visted, backup2, sizeof backup2);
		cin >> x >> y >> a >> b;
		dis[x][y] = 0;
		visted[x][y] = 1;
		queue<posi>q;
		q.push(posi(x, y));
		while (!q.empty())
		{
			posi temp = q.front();
			q.pop();
			if (temp.x == a && temp.y == b)
				cout << dis[a][b] << endl;
			else
			{
				int x_temp, y_temp;
				for (int i = 0; i < 8; i++)
				{
					x_temp = temp.x+xl[i];
					y_temp = temp.y+yl[i];
					posi temps(x_temp, y_temp);
					if (check_boundary(sizes, temps) && !visted[x_temp][y_temp])
					{
						q.push(temps);
						visted[x_temp][y_temp] = 1;
						dis[x_temp][y_temp] = dis[temp.x][temp.y] + 1;
					}
				}
			}
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Agreenhan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值