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;
}