Description
把1到n2的正整数从左上角开始由外层至中心按照顺时针方向螺旋排列
Input
输入整数n (1 <= n <= 10)
Output
按示例输出矩阵
Sample Input
3
4
Sample Output
1 2 3
8 9 4
7 6 5
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
C语言版本一
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int m,n;
int a[10][10];
int i,j;
while(scanf("%d",&n)!=EOF&&n<=20)
// while(scanf("%d %d",&n,&m)!=EOF&&n<=20&&m<=20)
{ m=n;
int count=1;
int left,right,up,down;
left=m;
right=-1;
up=0;
down=n;
int head;
head=1;
i=0;
j=0;
while(count<=n*m){
if(head==1)
{
a[i][j++]=count++;
if(j==left){
head=2;
left-=1;
j--;
i++;
}
}
else if(head==2)
{
a[i++][j]=count++;
if(i==down){
head=3;
down-=1;
i--;
j--;
}
}
else if(head==3)
{
a[i][j--]=count++;
if(j==right){
head=4;
right+=1;
j++;
i--;
}
}
else
{
a[i--][j]=count++;
if(i==up){
head=1;
up+=1;
i++;
j++;
}
}
}
if(n<=3){
for(i=0;i<=n-1;i++){
for(j=0;j<=m-2;j++){
printf("%-2d",a[i][j]);
}
printf("%d\n",a[i][j]);
}
}else if(n==10){
for(i=0;i<=n-1;i++){
for(j=0;j<=m-2;j++){
printf("%3d ",a[i][j]);
}
printf("%3d\n",a[i][j]);
}
}else{
for(i=0;i<=n-1;i++){
for(j=0;j<=m-2;j++){
printf("%2d ",a[i][j]);
}
printf("%2d\n",a[i][j]);
}
}
}
return 0;
}
C语言版本二
#include<stdio.h>
int main() {
int n, m, i, q, o, a[99][99];
while (scanf("%d%d", &n, &m) != EOF) {
if (m*n == 0)continue;
for (i = 1; i <= n; i++)
for (o = 1; o <= m; o++)
a[i][o] = 0;
q = o = 0;
i = 1;
while (q < m * n) {
for (o++; ; o++) { if (a[i][o] != 0||o>m) { o--; break; }q++; a[i][o] = q; }
for (i++; ; i++) { if (a[i][o] != 0||i>n) { i--; break; }q++; a[i][o] = q; }
for (o--; ; o--) { if (a[i][o] != 0||o<1) { o++; break; }q++; a[i][o] = q; }
for (i--; ; i--) { if (a[i][o] != 0||i<1) { i++; break; }q++; a[i][o] = q; }
}
for (o = 1; o <= n; o++) {
for (i = 1; i <= m; i++){
printf("%2d", a[o][i]);
if (i != m)printf(" ");
} printf("\n");}
}return 0;
}