洛谷P1443 马的遍历 简单BFS

13 篇文章 0 订阅

洛谷P1443 传送门

这题比较水,主要是要学一下优先队列和结构体一起使用的方法还有重载结构体的优先级


在这里插入图片描述


水题,初始化地图为-1,然后八个方向的bfs搜索即可

代码如下:

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <deque>
#include <cstring>
#include <iterator>
#include <set>
#include <map>
#define ll long long
using namespace std;
int mp[405][405];
int vis[405][405];
int mov[8][2] = {-2, -1, 2, 1, 2, -1, -2, 1, 1, 2, -1, -2, 1, -2, -1, 2};
int n, m, sx, sy;

struct horse
{
    int x, y, step;
} a, b;
queue<horse> q;
void bfs()
{
    while (!q.empty())
    {
        a = q.front();
        q.pop();
        mp[a.x][a.y] = a.step;
        for (int i = 0; i < 8; i++)
        {
            int xx = a.x + mov[i][0];
            int yy = a.y + mov[i][1];
            if (xx < 1 || yy < 1 || xx > n || yy > m || vis[xx][yy])
                continue;
            vis[xx][yy] = 1;
            b.x = xx;
            b.y = yy;
            b.step = a.step + 1;
            q.push(b);
        }
    }
}
int main()
{
    cin >> n >> m >> sx >> sy;
    memset(mp, -1, sizeof(mp));
    a.x = sx;
    a.y = sy;
    a.step = 0;
    q.push(a);
    vis[sx][sy] = 1;
    bfs();
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            printf("%-5d", mp[i][j]);
        cout << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hesorchen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值