考点:找规律
C++ 代码
做法1(完整代码):利用对称阵上下三角部分关于主对角线对称的性质
枚举每一行,每次从对角线元素处递增,同时由于是对称阵,把其对称位置也填上相同的数字
#include <iostream>
using namespace std;
const int N = 110;
int n;
int g[N][N];
void fill() {
for (int i = 0; i < n; i++) {
for (int j = i, num = 1; j < n; j++, num++) {
g[i][j] = g[j][i] = num;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << g[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}
int main() {
while (cin >> n, n) {
fill();
}
return 0;
}
做法2:每行的对角线元素开始向两侧递增填数
void fill() {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) cout << i - j + 1 << ' '; //填[i,i]以前的数
for (int j = i + 1; j < n; j++) cout << j - i + 1 << ' '; //填[i,i]以后的数
cout << endl;
}
cout << endl;
}
做法3:数字和坐标的关系:g[i][j] = abs(i - j) + 1
void fill() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) cout << abs(i - j) + 1 << ' ';
cout << endl;
}
cout << endl;
}
另类做法:蛇形填数法,来自题目 756. 蛇形矩阵
- 可按照题中对称阵的一些规律填数,但比较麻烦,代码也较长,仅仅作为一种可行思路
void fill() {
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1}; //上右下左的偏移量
//从[0,0]开始,从1开始填,先向右走//模式1表示递增,模式0表示递减
int x = 0, y = 0, num = 1, direction = 1, mode = 1;
for (int i = 0; i < n * n; i++) {
g[x][y] = num; //填数
int a = x + dx[direction], b = y + dy[direction]; //用变量a,b试探下一步是否撞墙
if (!(a >= 0 && a < n && b >= 0 && b < n && g[a][b] == 0)) { //如若撞墙,则
direction = (direction + 1) % 4; //顺时针改变一下方向
mode = 1 - mode; //切换模式
if (direction == 1) num = 0; //如果又回到了向右走,说明到了下一圈,重置一下num再开始填
}
x += dx[direction], y += dy[direction]; //改变当前坐标
if (mode) num++;
else num--;
}
//输出答案,顺便将g数组初始化
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << g[i][j] << ' ';
g[i][j] = 0;
}
cout << endl;
}
cout << endl;
}