20求助

P1443 马的遍历

cao_rui_xi @ 2024-12-08 15:16:29

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define AC 0
int n, m, x, y, s, t;
int vis[501][501];
int dx[8] = {1, 1, -1, -1, 2, 2, -2, 2};
int dy[8] = {-2, 2, -2, 2, -1, 1, 1, -1};
bool in(int x, int y) {
    return 1 <= x && x <= n && 1 <= y && y <= m;
}
struct node {
    int x, y, d;
};
queue<node> q;
signed main() {
    cin >> n >> m >> x >> y;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            vis[i][j] = -1;
        }
    }
    q.push(node{x, y, 0});
    vis[x][y] = 0;
    while (q.size()) {
        node f = q.front();
        q.pop();
        for (int i = 0; i < 8; i++) {
            int tx = f.x + dx[i];
            int ty = f.y + dy[i];
            if (in(tx, ty) && vis[tx][ty] == -1) {
                vis[tx][ty] = f.d + 1;
                q.push(node{tx, ty, f.d + 1});
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            printf("%-5lld", vis[i][j]);
        }
        cout << "\n";
    }
    return AC;
}

|