AcWing 寒假每日一题 2021-01-21 平方矩阵 II

AcWing 754. 平方矩阵 II(传送门)
在这里插入图片描述
在这里插入图片描述
思路分析:
找规律,不过有几个角度可以参考下,代码量逐渐变少。

第一种:
直接按行、列进行模拟

AC代码:

#include <iostream>

using namespace std;

const int N = 110;

int a[N][N];

int main() {
    
    
    int n;
    while (cin >> n && n) {
    
    
        for (int i = 1; i <= n; i++)
            for (int j = i, k = 1; j <= n; j++, k++) {
    
    
                a[i][j] = k;
                a[j][i] = k;
            }
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = 1; j <= n; j++)
                cout << a[i][j] << ' ';
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}

第二种:
观察对角线的左右,从左开始到对角线,是行数递减到1,然后是对角线的1开始递增

这样的话按行模拟即可,也貌似不用数组,代码量会小一些

AC代码:

#include <iostream>

using namespace std;

int main() {
    
    
    int n;
    while (cin >> n && n) {
    
    
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = i; j >= 1; j--)
                cout << j << ' ';
            for(int j = i + 1; j<=n;j++)
                cout << j - i + 1 << ' ';
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}

第三种:
U1S1,这种才是真正的找规律,如果把左上角的点的坐标记为 (1,1) 的话,那么每个数的值 = abs(横-纵) + 1

代码量是最短的!

AC代码:

#include <iostream>

using namespace std;

int main() {
    
    
    int n;
    while (cin >> n && n) {
    
    
        for (int i = 1; i <= n; i++) {
    
    
            for(int j = 1;j <= n;j++)
                cout << abs(i-j) + 1 << ' ';
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45654671/article/details/113002261