bfs50分剩下的Wa,求大佬调调
查看原帖
bfs50分剩下的Wa,求大佬调调
607834
yangCode01楼主2022/11/1 13:38
#include<bits/stdc++.h>

using namespace std;

struct node {
    int x, y;
    node(int xx, int yy) {
        x = xx, y = yy;
    }
};

int n, m, x, y;
queue<node> q;
int a[408][408];
int vis[408][408];
int dx[]{-2, -2, -1, 1, 2, 2, 1, -1};
int dy[]{-1, 1, 2, 2, 1, -1, -2, -2};

void bfs() {
    q.push(node(x, y));
    a[x][y] = 0;//起始点
    vis[x][y] = 1;
    while (!q.empty()) {
        int x=q.front().x;
        int y=q.front().y;
        q.pop();
        //马可以向八个方向走
        for (int i = 0; i < 8; i++) {
            int xx = x + dx[i];
            int yy = y + dy[i];
            if (xx >= 1 && yy >= 1 && xx <= n && yy <= m && !vis[xx][yy]) {
                a[xx][yy] = a[x][y] + 1;
                q.push(node(xx, yy));
                vis[xx][yy] = 1;
            }
        }
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> m >> x >> y;
    memset(a, -1, sizeof a);

    bfs();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            printf("%-5d", a[i][j]);
        }
        cout << endl;
    }
    return 0;
}

2022/11/1 13:38
加载中...