poj1915

本文介绍了一个经典的骑士周游问题,并通过使用广度优先搜索(BFS)算法来解决该问题。代码采用C++编写,实现了从起点到终点的最短路径寻找过程。此问题在计算机科学中常用于演示图遍历算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单题

ContractedBlock.gifExpandedBlockStart.gifView Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<queue>
using namespace std;

struct XPoint
{
int x, y;
int step;

} s, e;

#define maxn 306

int n;
bool vis[maxn][maxn];
int dir[8][2] =
{
{
1, 2 },
{
2, 1 },
{
-1, 2 },
{
-2, 1 },
{
-1, -2 },
{
-2, -1 },
{
1, -2 },
{
2, -1 } };

bool ok(XPoint &b)
{
if (b.x < 0 || b.y < 0 || b.x >= n || b.y >= n)
return false;
return !vis[b.x][b.y];
}

void bfs()
{
queue
<XPoint> q;
s.step
= 0;
q.push(s);
memset(vis,
0, sizeof(vis));
vis[s.x][s.y]
= true;
while (!q.empty())
{
XPoint a
= q.front();
q.pop();
for (int i = 0; i < 8; i++)
{
XPoint b;
b.x
= a.x + dir[i][0];
b.y
= a.y + dir[i][1];
b.step
= a.step + 1;
if (ok(b))
{
vis[b.x][b.y]
= true;
q.push(b);
}
if (b.x == e.x && b.y == e.y)
{
printf(
"%d\n", b.step);
return;
}
}
}
}

int main()
{
// freopen("t.txt", "r", stdin);
int t;
scanf(
"%d", &t);
while (t--)
{
scanf(
"%d", &n);
scanf(
"%d%d", &s.x, &s.y);
scanf(
"%d%d", &e.x, &e.y);
if (s.x == e.x && s.y == e.y)
{
printf(
"0\n");
continue;
}
bfs();
}
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值