广搜——马的遍历

https://www.luogu.com.cn/problem/P1443

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int s[400][400];
typedef struct qu
{
    int x, y;
} qu;
qu q[160000];
int t, h;

int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2};
int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1};

void dfs(int x, int y, int m, int n)
{
    q[t++] = {x, y};
    while (h != t)
    {
        auto [ux, uy] = q[h++];
        for (int i = 0; i < 8; i++)
        {
            int tx = ux + dx[i];
            int ty = uy + dy[i];
            if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && (s[ux][uy] + 1 < s[tx][ty])) //注意x这里是控制行,不像平面直角坐标系一样
            {
                s[tx][ty] = s[ux][uy] + 1;
                q[t++] = {tx, ty};
            }
        }
    }
}
int main()
{
    int m, n, x, y;
    scanf("%d%d%d%d", &n, &m, &x, &y);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            s[i][j] = 9999999;
        }
    }
    s[x][y] = 0;
    dfs(x, y, m, n);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            printf("%d\t", s[i][j] == 9999999 ? -1 : s[i][j]);
        }
        printf("\n");
    }
    system("pause");
    return 0;
}

posted @ 2023-02-08 10:02  MITE's_BKY  阅读(32)  评论(0)    收藏  举报