其他分享
首页 > 其他分享> > P1443 马的遍历

P1443 马的遍历

作者:互联网

题目链接

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

题目思路

经典宽搜问题,记住马走日!

题目代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
typedef pair<int, int> PII;
const int N = 410;
bool st[N][N];
int dist[N][N];
int n, m;

void bfs(int x, int y)
{
    queue<PII> q;
    q.push({x, y});
    dist[x][y] = 0;
    st[x][y] = true;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1}, dy[8] = {2, 1, -1, -2, 2, 1, -1, -2};
        for(int i = 0; i < 8; i ++)
        {
            int a = t.first + dx[i], b = t.second + dy[i];
            if(a >= 1 && a <= n && b >= 1 && b <= m && !st[a][b])
            {
                dist[a][b] = dist[t.first][t.second] + 1;
                st[a][b] = true;
                q.push({a, b});
            }
        }
    }
}

int main()
{
    int x, y;
    printf("%d%d%d%d", &n, &m, &x, &y);
    memset(dist, -1, sizeof dist);
    bfs(x, y);
    for(int i = 1; i <= n; i ++ )
    {
        for(int j = 1; j <= m; j ++ )
            printf("%-5d", dist[i][j]);
        puts("");
    }
        
    return 0;
}

标签:遍历,题目,P1443,int,dy,dist,include
来源: https://www.cnblogs.com/vacilie/p/16063579.html