1 条题解

  • 0
    @ 2025-10-26 15:41:58
    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    #define endl '\n'
    void solve() {
        int n; cin >> n;
        int a[n+1][n+1];
        int num = 1;
        for(int i = 1; i <= 2 * n - 1; i++){
            if(i&1){ 
                int row = (i <= n ? i : n);
                int col = (i <= n ? 1 : i - n + 1);
                while(row >= 1 && col <= n){
                    a[row][col] = num++;
                    row--;
                    col++;
                }
            }else{
                int row = (i <= n ? 1 : i - n + 1);
                int col = (i <= n ? i : n);
                while(row <= n && col >= 1){
                    a[row][col] = num++;
                    row++;
                    col--;
                }
            }
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){
                cout << a[i][j] << " ";
            }
            cout << '\n';
        }
    }
    signed main() {
        ios::sync_with_stdio(0);
        cin.tie(0),cout.tie(0);
        int T = 1;
        // cin >> T;
        while (T--)
            solve();
        return 0;
    }
    
    
    • @ 2025-10-26 15:48:08

      解题思路

      这道题要求蛇形填充 n x n 方阵,按左下 - 右上斜线编号(1 到 2 * n - 1),​奇数号斜线从左下到右上填充​,​偶数号斜线从右上到左下填充​。

      遍历每条斜线(共 2 * n - 1 条),根据斜线编号的奇偶性,确定填充方向和起始位置,逐个填充元素,最后输出方阵。

      找规律模拟,和幸运99里面的snack一个类型。

信息

ID
1157
时间
1000ms
内存
256MiB
难度
8
标签
递交数
16
已通过
6
上传者