MLE * 7求调

P1443 马的遍历

shuman @ 2024-08-07 10:06:30

看到其他楼主也有类似情况,试过了没用,求调

#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, steps[401][401];
bool vis[401][401];
int dx[8] = {-1, 1, -1, 1, 2, -2, 2, -2}, dy[8] = {2, 2, -2, -2, 1, -1, -1, 1};
queue<pair<int, int> > q;
int main()
{
    memset(steps, -1, sizeof(steps));
    memset(vis, false, sizeof(vis));
    cin >> n >> m >> x >> y;
    steps[x][y] = 0;
    q.push(make_pair(x, y));
    while (!q.empty())
    {
        int xx = q.front().first, yy = q.front().second;
        q.pop();
        vis[xx][yy] = true;
        for (int i = 0; i < 8; i++)
        {
            int nx = xx + dx[i], ny = yy + dy[i];
            if (!(nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny]))
            {
                steps[nx][ny] = steps[xx][yy] + 1;
                q.push(make_pair(nx, ny));
            }
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            printf("%-5d", steps[i][j]);
        cout << endl;
    }
    return 0;
}

by CATZZK @ 2024-08-07 10:18:20

#include <bits/stdc++.h>
using namespace std;
int n, m, x, y, steps[401][401];
bool vis[401][401];
int dx[8] = {-1, 1, -1, 1, 2, -2, 2, -2}, dy[8] = {2, 2, -2, -2, 1, -1, -1, 1};
queue<pair<int, int> > q;
int main()
{
    memset(steps, -1, sizeof(steps));
    memset(vis, false, sizeof(vis));
    cin >> n >> m >> x >> y;
    steps[x][y] = 0;
    vis[x][y]=true;
    q.push(make_pair(x, y));
    while (!q.empty())
    {
        int xx = q.front().first, yy = q.front().second;
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            int nx = xx + dx[i], ny = yy + dy[i];
            if (!(nx < 1 || nx > n || ny < 1 || ny > m || vis[nx][ny]))
            {
                steps[nx][ny] = steps[xx][yy] + 1;
                vis[nx][ny] = true;
                q.push(make_pair(nx, ny));
            }
        }
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            printf("%-5d", steps[i][j]);
        cout << endl;
    }
    return 0;
}

|