Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40703
  • 博文数量: 21
  • 博客积分: 825
  • 博客等级: 准尉
  • 技术积分: 235
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-06 18:08
文章分类

全部博文(21)

文章存档

2011年(1)

2010年(20)

我的朋友

分类: C/C++

2010-10-20 16:12:43

#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


阅读(335) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-10-21 10:06:49

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com