C++代码
AcWing 753. 平方矩阵 I
AcWing 755. 平方矩阵 III
AcWing 748 - 752
AcWing 727. 菱形
AcWing 3154. 打印大X
AcWing 118. 分形
#include<iostream>
using namespace std;
constexpr int N = 110;
int a[N][N];
int n;
int d[] = {-1,1};
int main()
{
while(cin >> n , n)
{
for(int i = 1; i <= n; ++i)
{
int b = i, c = 0;
for(int j = 1; j <= n; ++j)
{
a[i][j] = b;
if(b == 1) c = 1;
b += d[c];
}
}
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 2
2 1
1 2 3
2 1 2
3 2 1
1 2 3 4
2 1 2 3
3 2 1 2
4 3 2 1
1 2 3 4 5
2 1 2 3 4
3 2 1 2 3
4 3 2 1 2
5 4 3 2 1
从输出的样例,可以看出这是个n阶矩阵,每一行的第一个依次1 , 2 , 3 , 4 .... n; 故行遍历作为for的外循环
然后每一行先从第一个数减到1, 然后再从1开始加,直到每一行有n个数; 这个作为每一行的中列的遍历 –> for的内循环
故治理判断是减还是加,就算判断是否为1,1左边为递减, 1右边为递增.
每一行思路的代码简化 –> 参考y总
#include<iostream>
using namespace std;
int n;
int main()
{
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 , k = 2; j <= n; ++j) cout << k++ << " ";
cout << endl;
}
cout << endl;
}
return 0;
}
从对角线来看,1都位于对角线上,向右递增,向下递增.
#include<iostream>
using namespace std;
int arr[110][110];
int n;
int main()
{
while(cin >> n, n)
{
for(int i = 1; i <= n; ++i)
for(int j = i, k = 1; j <=n ; ++j, ++k)
arr[i][j] = k, arr[j][i] = k;
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= n; ++j)
cout << arr[i][j] << " ";
cout << endl;
}
cout << endl;
}
return 0;
}
两个横纵坐标规律 a[i][j] == abs(i-j) + 1; 通过观察
#include<iostream>
using namespace std;
int n;
int main()
{
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;
}