设为首页 加入收藏

TOP

打印螺旋序列 (一)
2014-11-23 21:12:48 来源: 作者: 【 】 浏览:31
Tags:打印 螺旋 序列

题目:给定一个数N(N = M^2 - 1)输出0、1、……、N的螺旋序列,其中M为正整数。

例如M为5时,输出如下序列。

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

解法:考虑设定一个(M + 2)^2大小的二维数组,边界部分赋值为-1,便于打印的时候识别边界,中间部分螺旋赋值。代码如下。

[cpp]
#include

#define MAX_BASE 100

using namespace std;

void fill_and_print(int _base)
{
int total = _base * _base;
int tofill[MAX_BASE + 2][MAX_BASE + 2];
memset(tofill, 0, sizeof(int) * (MAX_BASE + 2) * (MAX_BASE + 2));
tofill[0][0] = tofill[0][_base + 1] = tofill[_base + 1][0] = tofill[_base + 1][_base + 1] = -1;
for(int countBase = 0; countBase < _base; ++countBase)
{
tofill[0][countBase + 1] = -1;
tofill[_base + 1][countBase + 1] = -1;
tofill[countBase + 1][0] = -1;
tofill[countBase + 1][_base + 1] = -1;
}
int direction = 0; // 0 means right, 1 means down, 2 means left, 3 means up
int initColumn = 1;
int initRow = 2;
tofill[1][1] = -1;
for(int count = 1; count < total; ++count)
{
switch(direction)
{
case 0:
if(tofill[initColumn][initRow + 1] != 0)
{
tofill[initColumn++][initRow] = count;
direction = 1;
}
else
{
tofill[initColumn][initRow++] = count;
}
break;
case 1:
if(tofill[initColumn + 1][initRow] != 0)
{
tofill[initColumn][initRow--] = count;
direction = 2;
}
else
{
tofill[initColumn++][initRow] = count;
}
break;
case 2:
if(tofill[initColumn][initRow - 1] != 0)
{
tofill[initColumn--][initRow] = count;
direction = 3;
}
else
{
tofill[initColumn][initRow--] = count;
}
break;
case 3:
if(tofill[initColumn - 1][initRow] != 0)
{
tofill[initColumn][initRow++] = count;
direction = 0;
}
else
{
tofill[initColumn--][initRow] = count;
}
break;
default:
break;
}
}
tofill[1][1] = 0;
// print array
for(int countColumn = 1, countRow = 1; (countColumn < _base + 1) && (countRow < _base + 2);)
{
if(tofill[countColumn][countRow] == -1)
{
cout< ++countColumn;
countRow = 1;
continue;
}
else
{
cout< }
}
}

int main()
{
for(int testNumber = 1; testNumber < 11; ++testNumber)
{
cout<<"Array while base number equals "< fill_and_print(testNumber);
cout< }
return 0;
}

#include

#define MAX_BASE 100

using namespace std;

void fill_and_print(int _base)
{
int total = _base * _base;
int tofill[MAX_BASE + 2][MAX_BASE + 2];
memset(tofill, 0, sizeof(int) * (MAX_BASE + 2) * (MAX_BASE + 2));
tofill[0][0] = tofill[0][_base + 1] = tofill[_base + 1][0] = tofill[_base + 1][_base + 1] = -1;
for(int countBase = 0; countBase < _base; ++countBase)
{
tofill[0][countBase + 1] = -1;
tofill[_base + 1][countBa

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++ 中“空引用”与“空指针”的.. 下一篇POJ 2823 Sliding Window (RMQ +..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何理解c语言指针和 (2025-12-27 01:19:11)
·为什么C标准库没有链 (2025-12-27 01:19:08)
·玩转C语言和数据结构 (2025-12-27 01:19:05)
·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)