Description
将1~nn填入一个nn的矩阵中,并要求成为蛇形。蛇形即是从右上角开始向下,向左,向上,向右,循环填入数字。
比如n=5时矩阵为:
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5
Input
输入有多行,每行为一个整数n(1<=n<=50),每组答案用空行隔开。
Output
输出一个n*n的矩阵,n行n列每个数字用一个空格隔开,不能有多余空格。
Sample Input
5
Sample Output
13 14 15 16 1
12 23 24 17 2
11 22 25 18 3
10 21 20 19 4
9 8 7 6 5
不说啦,上代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
// 初始数组
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0
//0 0 0 0 0
//**************//
//13 14 15 16 1
//12 23 24 17 2
//11 22 25 18 3
//10 21 20 19 4
// 9 8 7 6 5
//明白蛇形矩阵走的方向,就可以轻易解决
int main()
{
int n;
scanf("%d",&n);
int a[n][n];
int cnt = 1;
int i = 0,j = n-1;
memset(a,0,sizeof(a));//数组置0 ,方便以下操作
a[i][j] = 1;
while(cnt<n*n)
{
//刚开始时我用的时if-else条件语句,但是发现很难找到可以控制的条件
//后来发现while循环更容易实现
while(a[i+1][j]==0&&i+1<n) //向下 ,若数组的值为 0,为其赋值,之后改变方向
{
a[++i][j] = ++cnt;
}
while(a[i][j-1]==0&&j-1>=0)//向左
{
a[i][--j] = ++cnt;
}
while(a[i-1][j]==0&&i-1>=0) //向上
{
a[--i][j] = ++cnt;
}
while(a[i][j+1]==0&&j+1<n) //向右
{
a[i][++j] = ++cnt;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}