全部评论 1

  • #include <iostream>
    #include <queue>
    using namespace std;
    
    int dist[401][401];
    const int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
    const int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};
    
    void bfs(int x, int y, int n, int m) {
        // 初始化
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                dist[i][j] = -1;
            }
        }
        dist[x][y] = 0;
        
        queue<pair<int, int>> q;
        q.push({x, y});
        
        while (!q.empty()) {
            auto [cx, cy] = q.front();
            q.pop();
            
            for (int k = 0; k < 8; k++) {
                int nx = cx + dx[k], ny = cy + dy[k];
                
                if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && dist[nx][ny] == -1) {
                    dist[nx][ny] = dist[cx][cy] + 1;
                    q.push({nx, ny});
                }
            }
        }
    }
    
    int main() {
        int n, m, x, y;
        cin >> n >> m >> x >> y;
        bfs(x, y, n, m);
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cout << dist[i][j] << " ";
            }
            cout << endl;
        }
        return 0;
    }
    

    2024-08-11 来自 广东

    0
首页