P1443 马的遍历

点击查看代码
#include<bits/stdc++.h>

using namespace std;

const int MAXN = 405;
int ans[MAXN][MAXN]; // 存储结果,同时也充当 visited 数组
int n, m, sx, sy;

// 马的8个方向
int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};

struct Point {
    int x, y;
};

void bfs() {
    //1.启动,初始化队列和矩阵把起点放入队列,并在第一个点上打勾
    queue<Point> q;
    memset(ans, -1, sizeof(ans));
    q.push({sx, sy});
    ans[sx][sy] = 0; // 起点步数为0

    //2.开始循环
    while (!q.empty()) {
        //取出
        Point curr = q.front();
        q.pop();

        // 观察(遍历所有邻居)
        for (int i = 0; i < 8; i++) {
            int nx = curr.x + dx[i];
            int ny = curr.y + dy[i];

            // 判断与入队
            if (nx < 1 || nx > n || ny < 1 || ny > m) continue;

           //如果没访问过就加上并入队
            if (ans[nx][ny] == -1) {
                ans[nx][ny] = ans[curr.x][curr.y] + 1;
                q.push({nx, ny});
            }
        }
    }
}

int main() {
    //读入矩阵形状和起始点
    cin >> n >> m >> sx >> sy;

    bfs();

    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            printf("%-5d", ans[i][j]); // %-5d 表示左对齐,宽5格
        }
        printf("\n");
    }

    return 0;
}
posted @ 2026-01-09 01:02  AnoSky  阅读(3)  评论(0)    收藏  举报