P1443 马的遍历

#include 
using namespace std;
int d[400][400];
struct node
{
    int x,y;
};
queue q;
int n,m,x,y;
bool check(int x,int y)
{
    return x >= 1 && x <= n && y >= 1 && y <= m && d[x][y] == -1;
}
int dx[] = {1,1,-1,-1,2,-2,2,-2};
int dy[] = {2,-2,2,-2,1,1,-1,-1};
int main()
{
    memset(d,-1,sizeof(d));
    cin >> n >> m >> x >> y;
    q.push({x,y});
    d[x][y] = 0;
    while(!q.empty())
    {
        node u = q.front();
        q.pop();
        int x = u.x,y = u.y;
        for(int i = 0;i < 8;i++)
        {
            int nx = x + dx[i],ny = y + dy[i];
            if(!check(nx,ny))   continue;
            q.push({nx,ny});
            d[nx][ny] = d[x][y] + 1;
        }
    }
    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++)
        {
            printf("%-5d ",d[i][j]);
        }
        cout << endl;
    }
    return 0;
}

你可能感兴趣的:(洛谷题解,c++,洛谷)