winlinglin

螺旋数组

今天想练练手,所以写了个螺旋数组:
  1 #include <iostream>
  2 
  3 using namespace std;
  4 
  5 #define MAXSIZE 8
  6 
  7 void left( int& x, int& y )
  8 {
  9     --y;
 10 }
 11 
 12 void right( int& x, int& y )
 13 {
 14     ++y;
 15 }
 16 
 17 void up( int& x, int& y )
 18 {
 19     --x;
 20 }
 21 
 22 void down( int& x, int& y )
 23 {
 24     ++x;
 25 }
 26 
 27 int main()
 28 {
 29     int numbers[MAXSIZE][MAXSIZE];
 30     // 初始化数组,若数值为0,则代表还没有被赋值
 31     forint i = 0; i<MAXSIZE; ++i )
 32         forint j = 0; j<MAXSIZE; ++j )
 33             numbers[i][j] = 0;
 34 
 35     enum Direction{RIGHT,DOWN,LEFT,UP};    // 移动方向
 36     int x=0,y=0;
 37     int Next = -1;    // 下一个位置的值
 38     Direction direct = RIGHT;
 39     int count = MAXSIZE * MAXSIZE;    // 还没被赋值的数目
 40     int value = 1;    //将要被赋值的值
 41 
 42     while( count > 0 )
 43     {
 44         Next = numbers[x][y];
 45         if( Next == 0 && x<MAXSIZE && y<MAXSIZE )    // 无障碍,可以赋值
 46         {
 47             numbers[x][y] = value;
 48             // 赋值成功,count减一, value加一
 49             --count;
 50             ++value;
 51 
 52             // 设置Next
 53             if( direct == RIGHT )
 54                 right( x, y );
 55             else if( direct == DOWN )
 56                 down( x, y );
 57             else if( direct == LEFT )
 58                 left( x, y );
 59             else if( direct == UP )
 60                 up( x, y );
 61         }
 62         else        // 有障碍,要转弯
 63         {
 64             if( direct == RIGHT )    // 若原来方向是右的话,就转弯向下
 65             {
 66                 x = x + 1;
 67                 y = y - 1;
 68                 direct = DOWN;
 69             }
 70             else if( direct == DOWN )    //若原来方向是下的话,就转弯向左
 71             {
 72                 x = x - 1;
 73                 y = y - 1;
 74                 direct = LEFT;
 75             }
 76             else if( direct == LEFT )    //若原来方向是左的话,就转弯向上
 77             {                
 78                 x = x - 1;
 79                 y = y + 1;
 80                 direct = UP;
 81             }
 82             else if( direct == UP)    //若原来方向是上的话,就转弯向右
 83             {                
 84                 x = x + 1;
 85                 y = y + 1;
 86                 direct = RIGHT;
 87             }
 88         }
 89     }
 90 
 91     forint i = 0; i<MAXSIZE; ++i )
 92     {
 93         forint j = 0; j<MAXSIZE; ++j )
 94         {
 95             cout<<numbers[i][j]<<"   ";
 96         }
 97         cout<<endl;
 98     }
 99 
100     return 0;
101 }

posted on 2009-03-05 18:33 wil 阅读(1086) 评论(2)  编辑 收藏 引用 所属分类: 算法

评论

# re: 螺旋数组 2009-03-06 09:02 成大才子

呵呵,有意思  回复  更多评论   

# re: 螺旋数组 2010-03-18 16:16 后现代

@成大才子
思路清晰,可改性强。 强  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2010年3月>
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

文章分类

搜索

最新评论

阅读排行榜

评论排行榜