Posted on 2008-03-28 09:56
王大头 阅读(126)
评论(0) 编辑 收藏 引用
这是大学学C语言得时候的一道习题。记得大学的时候写的有200行+哪,这次终于给改造短了。
^_^,我总是怀旧……
#include <stdio.h>

main(int argc,char *argv[])
{
int cube[100][100]={0};
int i=0,j=0,k=1,f=0,len=1,t=1;
int ARRSIZE=0;

if(argc!=2||atoi(argv[1])<1||atoi(argv[1])>100) { printf(" Usage : %s array_size(1-100) \n",argv[0]); }
else { ARRSIZE=atoi(argv[1]); }

for(k=1;k<=ARRSIZE*ARRSIZE;k++){
switch(f){
case 0: if (j+1>ARRSIZE-1) { cube[i++][j]=k; f=1; }
else if (cube[i][j+1]>0){ cube[i++][j]=k; f=1; }
else { cube[i][j++]=k; }
break;
case 1: if (i+1>ARRSIZE-1) { cube[i][j--]=k; f=2; }
else if (cube[i+1][j]>0){ cube[i][j--]=k; f=2; }
else { cube[i++][j]=k; }
break;
case 2: if (j-1<0) { cube[i--][j]=k; f=3; }
else if (cube[i][j-1]>0){ cube[i--][j]=k; f=3; }
else { cube[i][j--]=k; }
break;
case 3: if (i-1<0) { cube[i][j++]=k; f=0; }
if (cube[i-1][j]>0){ cube[i][j++]=k; f=0; }
else { cube[i--][j]=k; }
break;
default:
printf("The direction pointer is ERROR\n");
exit(1);
}
}

for(len=1;(ARRSIZE*ARRSIZE)>t;len++,t*=10) {};

for(i=0;i<ARRSIZE;i++){
for(j=0;j<ARRSIZE;j++) { printf("%*d ",len,cube[i][j]); }
printf("\n");
}
}