算法1
对角线都输入1,规律是从每行的对角线开始向右和向下递增
#include <iostream>
using namespace std;
sonst in N = 110;
int a[N][N];//数组比较大直接定义成全局数组避免因内存出错
int main()
{
int n;
while(cin >> n, n)
{
for (int i = 0; i < n; i ++)
{
for (int j = i, k = 1; j < n; j ++, k ++)
{
a[i][j] = k;
a[j][i] = k;
}
}
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < n; j ++)
{
cout << a[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}
return 0;
}
算法2
算法2 没用到数组 一行一行的输入 在对角点之前的部分从行号开始递减到1;对角点向右递增
注意二维矩阵里很多关系都是 j - i + 1之类的
#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, k = 2; j <= n; j ++,k ++) cout << k << ' ';
//有规律 可以改成 for (int j = i + 1; j <= n; j++ ) cout << j - i + 1<< ' ';
cout << endl;
}
cout << endl;
}
return 0;
}
算法3
算法3 就是规律 每个位置的值是 | i - j| + 1
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin >> n, n)
{
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < n; j ++)
cout << abs ( i - j ) + 1 << ' ';
cout << endl;
}
cout << endl;
}
return 0;
}