top1编程
← 返回题目
题解

【入门】对角线II

1 条题解

  • 0
    @ 2026-7-31 4:36:21

    解题思路

    这道题要求输出一个 N 行 N 列的方阵,其中只有反对角线(行号 + 列号 = N - 1 的位置)是 1,其他位置都是 0。

    比如 N=5:

    • 第 1 行:0 0 0 0 1
    • 第 2 行:0 0 0 1 0
    • 第 3 行:0 0 1 0 0
    • 第 4 行:0 1 0 0 0
    • 第 5 行:1 0 0 0 0

    与 P166 对角线I 的区别:

    • P166 是主对角线:i == j 时输出 1
    • P167 是反对角线:i + j == n - 1 时输出 1

    参考代码

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
    
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                // 反对角线:行号 + 列号 = n - 1 时输出 1
                if (i + j == n - 1) {
                    cout << setw(3) << 1;
                } else {
                    cout << setw(3) << 0;
                }
            }
            cout << endl;
        }
        return 0;
    }
    

    复杂度分析

    • 时间复杂度:O(N²)
    • 空间复杂度:O(1)
    • 1