题目描述 给出一个不大于 9 的正整数 n,输出 n×n 的蛇形方阵。
从左上角填上 1 开始,顺时针方向依次填入数字,如同样例所示。注意每个数字有都会占用 3 个字符,前面使用空格补齐。
输入 4 输出 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
思路: 方式1. 题目数据范围实在是太小了,可以直接采用打表的方式. 方式2. 矩阵依次是1 ~ n*n 的数, 从左往右,从上往下,再从右往左,下往上. 所以只要循环的方式可以实现"蛇形"就可以得到答案.
![循环遍历的方式](https://img-blog.csdnimg.cn/63aae37d57f34c78b8ef75bb2207dcfa.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA57qv5oOF56iL5bqP54y_,size_15,color_FFFFFF,t_70,g_se,x_16)
Copy 方式 2 :
#include
int a[10][10]; //这里定义全局变量,默认数组每个元素初始化为 0
int main(){
int n;
int k = 0; // 蛇形走位的初始值,每次循环成功 ++k;
scanf("%d",&n);
int x = 1,y = 0;
while( k a[x][++y] = ++k;}
//从上往下 ,
while( x a[x][--y] = ++k;}
//从下往上
while( x > 1 && a[x-1][y] == 0 )
{ a[--x][y] = ++k;}
}
for(int i = 1; i
printf("%3d",a[i][j]);
}
printf("\n");
}
return 0;
}
Copy 方式1:
#include
using namespace std;
int n;
int main () {
cin >> n;
if(n == 1)
cout
cout
cout
cout |