#include <stdio.h>
#define N 5
int que[100]; //队列
int head=0; //队列头
int tail=0; //队列尾
void initQue(){
que[0] = N;
que[1] = N;
que[2] = -1;
tail = 3;
}
int getHead(){
return que[head++];
}
void push(int a){
que[tail] = a;
tail ++;
}
int main(int argc, char ** argv){
int a[N][N],i,j,cnt;
a[0][0] = 1;
j = i = 0;
cnt = 0;
initQue();
int h;
while(1){
h = getHead();
if(N%2 != 0 && i == (N-1)/2 && j == (N-1)/2){
break;
}else if(N%2 == 0 && i== N/2 && j == N/2-1){
break;
}
if(cnt%2 == 0){
if(cnt%4 == 0){
push(i);
for(j=j+1;j<h;j++){
a[i][j] = a[i][j-1] + 1;
}
j--;
}
else if(cnt%4 == 2){
push(i);
for(j=j-1;j>h;j--){
a[i][j] = a[i][j+1] + 1;
}
j++;
}
}else{
if(cnt%4 == 1){
push(j);
for(i=i+1;i<h;i++){
a[i][j] = a[i-1][j] + 1;
}
i--;
}
else if(cnt%4 == 3){
push(j);
for(i=i-1;i>h;i--){
a[i][j] = a[i+1][j] + 1;
}
i++;
}
}
cnt ++;
}
for(i=0;i<N;i++){
for(j=0;j<N;j++){
printf("%d\t",a[i][j]);
}
printf("\n");
}
return 0;
}
输出结果:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
|