Problem D: 蛇形填阵
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
HINT
Append Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main(){
int n = 0;
while(scanf("%d",&n) != EOF){
int a[n][n];
int i = 1;
int j = 0;
int rdown = n - 1,cleft = n - 1;
int rup = 0,cright = 0;
int k = rdown;
for(i = 1;i <= n * n;){
//下行
for(j = cright;j <= cleft;j++){
a[j][rdown] = i;
i++;
}
rdown--;
if(rdown < rup)break;
//左行
for(k = rdown;k >= rup;k--){
a[cleft][k] = i;
i++;
}
cleft--;
if(cleft < cright)break;
//上行
for(j = cleft;j >= cright;j--){
a[j][rup] = i;
i++;
}
rup++;
if(rdown < rup)break;
//右行
for(k = rup;k <= rdown;k++){
a[cright][k] = i;
i++;
}
cright++;
if(cleft < cright)break;
}
i = 0;
for(i = 0;i < n;i++){
printf("%d",a[i][0]);
for(j = 1;j < n;j++){
printf(" %d",a[i][j]);
}
printf("\n");
}
printf("\n");
}
}