飛天

快乐的生活......

 

[ACM 1005] 做幻方

做幻方
Time Limit:1000MS  Memory Limit:1024K

Description:

Apple最近迷上了做幻方,Apple还是个中高手,只要你说个奇数N就能把N*N的幻方做出来。其实你可以比他做得更好的。Apple总是画得很乱,而你可以利用程序排得很整齐^_^ 幻方的要求:每一行,每一列,还有两条斜线上数字的和都相等

Input:

每行一个数N(0< N < 30),输入0结束

Output:

输入一个奇数,输出一个幻方,每个数占3格,顺序参照样板输出,输出完以后加一个回车。

Sample Input:

5
1
0

Sample Output:

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

Hint:

如果不会做幻方的请从1开始数到最后,相信你会发现其中的规律。当然输出也要按照这样的格式

Source:

Zhang Anping
#include <iostream>
using namespace std;

#define MAX 30


static int data[30][30];

void solve(int n)
{
    
  
int i;
  
int _x=1,_y=1;
  
int index=1;
  
int x=n-1,y=n/2;
  
  
for( i=0;i<n;i++)
  
{
      
for(int j=0;j<n;j++)
          data[i][j]
=0;
     
  }


  
while(index<=n*n)
  
{
        data[x][y]
=index;
        
int newx=x+_x;
        
int newy=y+_y;
        
if(newx>=n) newx=0;
        
if(newy>=n) newy=0;
        
if(data[newx][newy]!=0)
        
{
            x
--;
        }

        
else
        
{
            x
=newx;y=newy;
        }

        index
++;
  }


 


  
for( i=0;i<n;i++)
  
{
      
for(int j=0;j<n;j++)
          printf(
"%3d",data[i][j]);
      cout
<<endl;
  }

  cout
<<endl;
}


int main(int argc, char* argv[])
{
    
int input;
    
while(cin>>input&&input!=0)
    
{
        
if(input%2==0continue;
        
if(input>0&&input<30)
            solve(input);
    }

    
return 0;

}

posted on 2008-01-20 14:31 飛天 阅读(574) 评论(0)  编辑 收藏 引用 所属分类: ACM


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


导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

文章分类

文章档案

Blogs

搜索

最新评论

阅读排行榜

评论排行榜