实现回形数

一个画图程序 要求打印出

   

int i=5;

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

   

int i=6

1 2 3 4 5 6

20 21 22 23 24 7

19 32 33 34 25 8

18 31 36 35 26 9

17 30 29 28 27 10

16 15 14 13 12 11

   

这里加一个限制,i<=25。

   

题目很简单,大一学生分分钟就能写出来。

语言不限,常规语言都行,C/C++/Java/C#/Ruby/Python/Perl。

代码简洁易懂为佳。(这里算是一个反例: http://www.javaeye.com/topic/557924

   

   

花了一个小时的时间弄了一下

按照自顶向下的算法设计思路,数组的数按照回形形状摆放,赋值的时候按照

顺时针的方式,先赋值最上面的一行,然后是右边的一列,然后是下边的一行,最后是左边的一行构成一个圈,

每构造完一圈,每行的数据的个数要减2。

   

   

#include<iostream>

using namespace std;

int main()

{

int k=0;

   

cout<<"input number"<<endl;

int **a;

int i,j;

cin>>k;

   

a=new int *[k];

for(i=0;i<k;i++)

{

a[i]=new int[k];

}

   

for(i=0;i<k;i++)

for(j=0;j<k;j++)

{

a[i][j]=0;

}

   

/*赋值回形数*/

int col=0,row=0;

int num=1;

int count;

int tempRow;

   

/*

按照顺时针的方式赋值数组

*/

for(i=k;i>=0;i=i-2)

{

   

tempRow=row;

count=0;

col=row;

   

//i代表每行要赋值的个数

   

while(count<i)

{

a[row][col]=num;

count++;

num++;

col++;

}

   

col--;

   

for(row++;row<=col;row++)

{

a[row][col]=num;

num++;

}

   

row--;

   

for(col--;col>=tempRow;col--)

{

a[row][col]=num;

num++;

}

   

col++;

   

for(row--;row>tempRow;row--)

{

a[row][col]=num;

num++;

}

   

row=tempRow;

row++;

}

   

   

//输出二维数组

for(i=0;i<k;i++)

{

for(j=0;j<k;j++)

{

cout<<" , "<<a[i][j];                

}

cout<<endl;

}

return 0;

}

   

posted @ 2009-12-28 22:11  smile2you  阅读(464)  评论(0编辑  收藏  举报