Knight moves

Knight moves

在这里插入图片描述
在这里插入图片描述
题目分析
bfs宽度优先搜索

代码

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int t, n;
int sx, sy, ex, ey, nx, ny;
int book[305][305];
int dir[8][2] = { {2,-1},{2,1},{1,-2},{1,2},{-1,2},{-1,-2},{-2,-1},{-2,1} };
struct knight
{
	int x;
	int y;
	int step;
}fa, son;
void bfs(int sx, int sy)
{
	queue<knight>q;
	int x, y, step;
	fa.x = sx;
	fa.y = sy;
	fa.step = 0;
	q.push(fa);
	memset(book,0, sizeof(book));
	while (!q.empty())
	{
		knight fa = q.front();
		q.pop();
		if (fa.x == ex && fa.y == ey)
		{
			cout << fa.step << endl;
			break;
		}
		for (int k = 0; k < 8; k++)
		{
			nx = fa.x + dir[k][0];
			ny = fa.y + dir[k][1];
			if (nx >= 0 && ny >= 0 && nx < n && ny < n && book[nx][ny] == 0)
			{
				knight son;
				son.x = nx;
				son.y = ny;
				son.step = fa.step + 1;
				book[nx][ny] = 1;
				q.push(son);
			}
		}
	}
}
int main()
{
	cin >> t;
	while (t--)
	{
		cin >> n;
		cin >> sx >> sy >> ex >> ey;
		bfs(sx, sy);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值