洛谷P1443 马的遍历的纯代码题解

之前的二分题解就全部告一段落啦!现在来看搜索
而马的遍历是一道非常典型的bfs,这里用队列来实现比较方便

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define MAXN 405
using namespace std;
typedef struct coordinate{
    int x, y;
}coor;
coor horse;
queue <coor> q;
int chest[MAXN][MAXN];
int n, m;
int walk[8][2] = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};

void print()
{
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= m; j ++)
        {
            printf("%-5d", chest[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    scanf("%d%d%d%d", &n, &m, &horse.x, &horse.y);
    memset(chest, -1, sizeof(chest));
    q.push(horse);
    chest[horse.x][horse.y] = 0;
    while(!q.empty())
    {
        int temx, temy;
        coor first = q.front();
        coor tem;
        q.pop();
        for(int i = 0; i < 8; i ++)
        {
            temx = first.x + walk[i][0];
            temy = first.y + walk[i][1];
            if(temx < 1 || temy < 1 || temx > n || temy > m || chest[temx][temy] != -1) continue;
            chest[temx][temy] = chest[first.x][first.y] + 1;
            tem.x = temx;
            tem.y = temy;
            q.push(tem);
        }
    }
    print();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值