编程输出以下格式的数据。(趣味题)
When i=0
1
When i=1
7 8 9
6 1 2
5 4 3
When i=2
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
typedef struct _Pos{
int x;
int y;
}POS,*PPOS;
POS NextPosition(int dir,POS pos){
switch(dir){
case 0:{
pos.y += 1;
break;
}
case 1:{
pos.x += 1;
break;
}
case 2:{
pos.y -= 1;
break;
}
case 3:{
pos.x -= 1;
break;
}
}
return pos;
}
void show(unsigned char **buf,const int N){
for(int i=0;i<N;i++){
for(int j = 0;j<N;j++){
printf("%5d ",buf[i][j]);
}
printf("\n");
}
}
void GetResult(int n){
const int N = 2*n + 1;
unsigned char **result = (unsigned char **)malloc(N * sizeof(unsigned char*));
int i = 0, j= 0;
for(i = 0;i<N;i++){
result[i] = (unsigned char *)malloc(N * sizeof(unsigned char));
memset(result[i],0,N);
}
int InitValue = 1;
POS InitPos = {n,n};
POS curPos = InitPos,NextPos = {0,0};
result[curPos.x][curPos.y] = InitValue++;
int dir = 0;
while(1){
NextPos = NextPosition(dir,curPos);
if(result[NextPos.x][NextPos.y] != 0){
dir = dir -1;
if(dir <0) dir = 3;
NextPos = NextPosition(dir,curPos);
}
dir += 1;
dir %= 4;
curPos = NextPos;
printf("dir %d pos %d %d\n",dir,curPos.x,curPos.y);
if(InitValue > N * N) {
break;
}
result[curPos.x][curPos.y] = InitValue++;
}
show(result,N);
for(i=0;i<N;i++){
free(result[i]);
}
}
微信
支付宝