当前位置:编程学习 > C/C++ >>

打印螺旋序列

题目:给定一个数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 <iostream>  
 
#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; 
    // pr

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,