This blog has been shut down permanently.

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  13 随笔 :: 0 文章 :: 25 评论 :: 0 Trackbacks

1   2   3     4
12 13  14   5
11 16  15   6
10  9    8    7  

这种情况用模拟比较好推出,以1为坐标原点,一次递增,遇到边界则转向

#include<stdio.h>
#include
<string.h>
#define MAX_SIZE 100
const int intx[]= {0,1,0,-1};
const int inty[]= {1,0,-1,0};
int main() 

   
int dir,i,j,n,data,x,y,nextx,nexty;
   
int arr[MAX_SIZE][MAX_SIZE];
   
/*Read size*/
   printf(
"please input the size\n");
   scanf(
"%d",&n);
   
/*Init*/
   x
= y= 0;
   dir
= 0;
   memset(arr,
0,sizeof(arr));
   
/*fill*/
   
for(data=1; data<=n*n; data++)
   
{
       arr[x][y]
= data;
       nextx
= x+intx[dir];
       nexty
= y+inty[dir];
       
if(arr[nextx][nexty] || nextx>=|| nexty>=|| nextx<0 || nexty<0)
       
{
           dir
++;
           
if(dir==4)dir=0;
       }

       x
+= intx[dir];
       y
+= inty[dir];
   }

   
for(i=0; i<n; i++)
   
{
       
for(j=0; j<n; j++)
           printf(
"%d\t",arr[i][j]);
       printf(
"\n");
   }

}

 

如果碰到另外一种情况就麻烦多了

          21  22................
           20  7  8  9  10
           19  6  1  2  11
           18  5  4  3  12
           17  16 15 14 13

如果从中间开始模拟

从原点1开始,看方向的变化:右下左上;行走的步数:11223344……

 公式:n^2= 1+1+2+2+...+n-1+n-1+n(第一种情况也有用到)

有了公式,那就可以先算出最大的data是多少,这样又转换为第一种方法了。

如果没有公式,单纯对行为进行模拟难度很大,不过还是可以实现的。

现在暂时还没有想到实现的方法,想到以后再补充吧。
 

posted on 2009-11-15 16:02 iZ 阅读(3246) 评论(4)  编辑 收藏 引用 所属分类: 『Algorithm,Data Structure in C++』

评论

# re: 螺旋矩阵的算法 2009-11-17 16:39 qinqing1984
这个模型比较简单,从中间向外转,就有点复杂了  回复  更多评论
  

# re: 螺旋矩阵的算法 2009-11-18 17:02 xuxiandi
从中间向外转....不就是从外向中间转..然后递减吗?  回复  更多评论
  

# re: 螺旋矩阵的算法 2009-11-19 13:44 iSsay
@xuxiandi
我在想如果没有数学公式该怎么模拟呢

现在还想不出来,因为循环控制不好弄,要用到很多变量标记  回复  更多评论
  

# re: 螺旋矩阵的算法 2012-10-22 00:07 光亮
if(arr[nextx][nexty] || nextx>=n || nexty>=n || nextx<0 || nexty<0)

作者这句话有点小错误。。第一个判断放到最后更好  回复  更多评论
  


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