逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::
输入一个自然数N(2≤N≤9),要求输出如下的魔方阵,即边长为N*N,元素取值为1至N*N,1在左上角,呈顺时针方向依次放置各元素。
N
=3时:
1 2 3
8 9 4
7 6 5
【输入形式】
从标准输入读取一个整数N。 
【输出形式】
向标准输出打印结果。输出符合要求的方阵,每个数字占5个字符宽度,向右对齐,在每一行末均输出一个回车符。
【输入样例】 
4
【输出样例】
 
1  2  3  4
12 13 14  5
11 16 15  6
10  9  8  7  
#include <iostream>

void fantasy(const int n) {
    
int array[n][n];
    
int topLeft[2= { 00 };
    
int topRight[2= { 0, n - 1 };
    
int bottomRight[2= { n - 1, n - 1 };
    
int bottomLeft[2= { n - 10 };

    
int row, col;
    
int counter = 0;
    
while (true) {
        
// Go right.
        row = topLeft[0];
        col 
= topLeft[1];
        
while (col <= topRight[1]) {
            array[row][col
++= ++counter;
        }
        topRight[
0+= 1;
        topRight[
1-= 1;

        
// Go down.
        row = topRight[0];
        col 
= topRight[1+ 1;
        
while (row <= bottomRight[0]) {
            array[row
++][col] = ++counter;
        }
        bottomRight[
0-= 1;
        bottomRight[
1-= 1;

        
// Go left.
        row = bottomRight[0+ 1;
        col 
= bottomRight[1];
        
while (col >= bottomLeft[1]) {
            array[row][col
--= ++counter;
        }
        bottomLeft[
0-= 1;
        bottomLeft[
1+= 1;

        
// Go up.
        row = bottomLeft[0];
        col 
= bottomLeft[1- 1;
        
while (row > topLeft[0]) {
            array[row
--][col] = ++counter;
        }
        topLeft[
0+= 1;
        topLeft[
1+= 1;

        
// End ?
        if (topLeft[1>= topRight[1]) {
            
if (n % 2 != 0) {
                array[n 
/ 2][n / 2= ++counter;
            }
            
break;
        }
    }

    
// Output the result.
    for (int row = 0; row < n; ++row) {
        
for (int col = 0; col < n; ++col) {
            std::cout 
<< array[row][col] << "\t";
        }
        std::cout 
<< std::endl;
    }
}

int main() {
    
for (int i = 2; i <= 9++i) {
        fantasy(i);
        std::cout 
<< std::endl;
    }

    
return 0;
}
联珠顶真的回文诗:
莺啼岸柳
   月明弄
   夜睛春

莺啼岸柳弄春睛
柳弄春睛夜月明
明月夜睛春弄柳
睛春弄柳岸啼莺

posted on 2008-04-22 15:06 逛奔的蜗牛 阅读(892) 评论(0)  编辑 收藏 引用 所属分类: C/C++

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