大佬们求调
查看原帖
大佬们求调
796997
CandyGodOfWar楼主2024/12/5 09:50
#include<iostream>
#include<queue>
#include<cstring>
#define int long long
using namespace std;
const int N = 405;
int n, m, bx, by, dir[8][2] = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {-1, 2}, {1, -2}, {-1, -2}}, ex, ey, f[N][N], INF;
struct node {
    int x, y, cnt;
};
queue<node>que;
void bfs () {
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            f[i][j] = -1;
        }
    }
    INF = f[1][1];
    f[bx][by] = 0;
    que.push({bx, by, 0});
    while (que.size()) {
        node head = que.front();
        que.pop();
        if (head.x == ex && head.y == ey) {
            return;
        }
        for (int i = 0; i < 8; i++) {
            int tx = head.x + dir[i][0];
            int ty = head.y + dir[i][1];
            if (tx >= 1 && tx <= n && ty >= 1 && ty <= m && f[tx][ty] == -1) {
                f[tx][ty] = head.cnt + 1;
                que.push({tx, ty, head.cnt +1});
            }
        }
    }
}
signed main () {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> bx >> by;
    ex = n;
    ey = m;
    bfs();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (i == bx && j == by) {
                cout << "0 ";
            }
            else if (f[i][j] == INF) {
                cout << "-1 ";
            }
            else {
                cout << f[i][j] << " ";
            }
        }
        cout << "\n";
    }
    return 0;
}
2024/12/5 09:50
加载中...