C++ 螺旋矩阵算法

清理磁盘空间的时候翻出了多年前写过的螺旋矩阵,代码效率和水平较低,纪念一下,保存到博客园!

// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;

///////////螺旋矩阵,从外往里///////////

class Point
{
public:
    int x;
    int y;
    Point()
    {
        x=0;
        y=0;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    loop:
    int width=0,state=1,Number=1;
    std::cout<<"请输入宽度:";
    cin>>width;
    
    Point LeftTop,RightTop,RightBottom,LeftBottom;
    RightTop.x=width;
    RightBottom.x=width;
    RightBottom.y=width;
    LeftBottom.y=width;

    //初始化数组
    int **arr=new int *[width];
    for(int len=0;len<width;arr[len++]=new int[width]());

    while (Number<=(width*width))
    {
        if (1==state)
        {
            for (int i = LeftTop.x; i < RightTop.x ; i++)
            {
                arr[LeftTop.y][i]=Number++;
            }
            LeftTop.y=++RightTop.y;
            state=2;
            continue;
        }
        if (2==state)
        {
            for (int i = RightTop.y; i < RightBottom.y; i++)
            {
                arr[i][RightTop.x-1]=Number++;
            }
            RightTop.x=--RightBottom.x;
            state=3;
            continue;
        }
        if (3==state)
        {
            for (int i = RightBottom.x-1; i >= LeftBottom.x; i--)
            {
                arr[LeftBottom.y-1][i]=Number++;
            }
            RightBottom.y=--LeftBottom.y;
            state=4;
            continue;
        }
        if (4==state)
        {
            for (int i = LeftBottom.y-1; i >= LeftTop.y; i--)
            {
                arr[i][LeftTop.x]=Number++;
            }
            LeftTop.x=++LeftBottom.x;
            state=1;
            continue;
        }
    }

    std::cout<<endl;

    //输出
    for(int x=0;x<width;x++)
    {
        for(int y=0;y<width;y++)
        {
            std::cout<<setw(5)<<arr[x][y];
        }
        std::cout<<endl<<endl;
    }
    std::cout<<endl<<endl;
    goto loop;
    return 0;
}

 

posted @ 2017-07-04 14:18  叶图大师  阅读(3126)  评论(0编辑  收藏  举报