蛇形数组

来源:互联网 发布:淘宝v6会员怎么没了 编辑:程序博客网 时间:2024/06/11 06:16

今天买了本《算法竞赛 入门经典》来看,真是觉得惭愧,别人初中生就懂得东西我现在大学才开始看,唉......

 

觉得书里面的算法挺神奇就发上来了。

 

输入:

4

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

 

 

C++语言: Codee#12066
#include <iostream>
#include <string>
#include <iomanip>

const int MAXN = 10;
int a[ MAXN ][ MAXN ];

int main()
{
    int n, x, y, total = 0;
    std::cin >> n;

    std::memset( a, 0, sizeof( a ) );

    // 设置当前要写的数为 1, 并把第一个数写上去
    total = a[ x = 0 ][ y = n - 1 ] = 1;

    // 右 下 左 上
    // 只写等于 0 的 a[][],已经写过的不再写
    while ( total < n * n )
    {
        while ( x + 1 < n && ! a[ x + 1 ][ y ] )    a[ ++x ][ y ] = ++total;
        while ( y - 1 >= 0 && ! a[ x ][ y - 1 ] )    a[ x ][ --y ] = ++total;
        while ( x - 1 >= 0 && ! a[ x - 1 ][ y ] )    a[ --x ][ y ] = ++total;
        while ( y + 1 < n && ! a[ x ][ y + 1 ] )    a[ x ][ ++y ] = ++total;
    }

    for ( int i = 0; i < n; i++ )
    {
        for ( int j = 0; j < n; j++ )
        {
            std::cout << std::setiosflags( std::ios::left ) << std::setw( 3 ) << a[ i ][ j ];
        }
        std::cout << std::endl;
    }

    return 0;
}
原创粉丝点击