蛇形数组
来源:互联网 发布:淘宝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;
}
#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;
}
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形数组
- 蛇形输出数组问题
- //输出蛇形数组
- 使用CSplitterWnd类分割窗口
- 论函数调用约定
- 哈哈,新手上路了
- .Net基础:学习反射中的动态创建对象
- Ubuntu中Document View 中文显示乱码解决办法
- 蛇形数组
- 解决一个Linux下C语言工程无法调试的问题
- vc中遇到错误提示:nafxcwd.lib(thrdcore.obj) : error LNK2001: unresolved external symbol __endthreadex
- 诸神之战
- 超级链接标记详解
- Android Opencore PVPlayer
- 这哥们我太爱了
- 工程师淘金:开发Android主攻四大方向
- sql求两个表的差