例:在n*n方阵里输入1,2,3,...,n*n,要求填成蛇形。例如n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中,多余的空格知识为了便于观察矩阵,不必严格输出,n<=8。
解:此题需要小小地思考下:在按蛇形填充矩阵的过程中,我们注意到这个固定的过程:下、左、上、右、下、左、上、右... ...这个过程是循环的,也就是说我们找到了解决问题的规律~接下来只要模拟这个过程就可以了!
Code:
#include<stdio.h>
#include<string.h>
int a[10][10];
int main()
{
int i, j, n, count;
memset(a, 0, sizeof(a));
scanf("%d", &n);
count = a[i = 1][j = n] = 1;//赋初值,方向为:右->左
while(count < n*n)
{
while(i<n && !a[i+1][j]) a[++i][j] = ++count;//下
while(j>1 && !a[i][j-1]) a[i][--j] = ++count;//左
while(i>1 && !a[i-1][j]) a[--i][j] = ++count;//上
while(j<n &am