1 条题解

  • 0
    @ 2026-8-17 9:05:03
    #include <bits/stdc++.h>
    #include <algorithm>
    #define LL long long
    using namespace std;
    const LL N = 500;
    LL n, m, a, b, vis[N][N], k[N][N];
    LL dx[] = {0, -2, -1, 1, 2, 2, 1, -1, -2}, dy[] = {0, 1, 2, 2, 1, -1, -2, -2, -1};
    // 八个方向
    struct CCTV
    {
      LL x, y; // 坐标
    };
    void bfs(LL x, LL y)
    {
      queue<CCTV> q; // bfs 模版
      k[x][y] = 0;   // 起点
      q.push({x, y});
      vis[x][y] = 1; // 标记已经走过
      while (q.size())
      {
        CCTV now = q.front(); // 取出坐标,应用结构体存储
        q.pop();
        for (int i = 1; i <= 8; i++)
        {
          LL nx = now.x + dx[i], ny = now.y + dy[i];
          // 获得八个方向
          if (nx > 0 && nx <= n && ny > 0 && ny <= m && !vis[nx][ny])
          {
            k[nx][ny] = k[now.x][now.y] + 1; // 步数++
            q.push({nx, ny});                // 加入队列, 可以往后走
            vis[nx][ny] = 1;                 // 标记已经走过
          }
        }
      }
    }
    int main()
    {
      cin.tie(0);
      cout.tie(0);
      cin >> n >> m >> a >> b;
      memset(k, -1, sizeof(k)); // 全部设置成 -1 如果有到达不了的点,可直接输出
      bfs(a, b);
      for (int i = 1; i <= n; i++)
      {
        for (int j = 1; j <= m; j++)
        {
          if (i == a && j == b)
            cout << "0 "; // 起点
          else
            cout << k[i][j] << " ";
        }
        cout << "\n";
      }
      return 0;
    }
    
    
    • 1

    信息

    ID
    12652
    时间
    1000ms
    内存
    150MiB
    难度
    6
    标签
    递交数
    17
    已通过
    11
    上传者