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

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

#include 
#include 
#include 
#include 
#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;
}

你可能感兴趣的:(刷题代码)