【「POJ1915」Knight Moves】题解

原题目链接:Link

gm : bfs的版题

没学过 bfs 的同学可以看代码注释,先理解意思。

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int Maxn = 300 + 5;
const int a[8] = {-2, -1, 1, 2, 2, 1, -1, -2}; // 增量数组
const int b[8] = {1, 2, 2, 1, -1, -2, -2, -1};
int n, l, sx, sy, ex, ey;
bool vis[Maxn][Maxn]; 
struct node {
	int x, y, step;
};
int bfs() {
	queue<node> q; // 定义队列
	q.push((node){sx, sy, 0}); // 存入起点信息
	while(!q.empty()) { // 非空
		node p = q.front();
		q.pop(); 
		if(p.x == ex and p.y == ey) return p.step; // 是否到达终点
		for(int i = 0;i < 8; ++i) {
			int dx = p.x + a[i], dy = p.y + b[i]; // 在当前坐标的基础上能直接到达的新坐标
			if(dx >= 0 and dy >= 0 and dx < l and dy < l and !vis[dx][dy]) { // 判断是否可以到达
				vis[dx][dy] = 1; // 已经搜索
				q.push((node){dx, dy, p.step + 1}); // 存入新的信息
			}
		}
	} 
}
int main() {
	scanf("%d", &n);
	while(n --) {
		memset(vis, 0, sizeof(vis));
		scanf("%d %d %d %d %d", &l, &sx, &sy, &ex, &ey); // 不要被题目介绍熏昏了头脑
		printf("%d\n", bfs());
	}
	return 0;
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值