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

// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std; ///////////螺旋矩阵,从外往里/////////// class Point
{
public:
int x;
int y;
Point()
{
x=;
y=;
}
}; int _tmain(int argc, _TCHAR* argv[])
{
loop:
int width=,state=,Number=;
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=;len<width;arr[len++]=new int[width]()); while (Number<=(width*width))
{
if (==state)
{
for (int i = LeftTop.x; i < RightTop.x ; i++)
{
arr[LeftTop.y][i]=Number++;
}
LeftTop.y=++RightTop.y;
state=;
continue;
}
if (==state)
{
for (int i = RightTop.y; i < RightBottom.y; i++)
{
arr[i][RightTop.x-]=Number++;
}
RightTop.x=--RightBottom.x;
state=;
continue;
}
if (==state)
{
for (int i = RightBottom.x-; i >= LeftBottom.x; i--)
{
arr[LeftBottom.y-][i]=Number++;
}
RightBottom.y=--LeftBottom.y;
state=;
continue;
}
if (==state)
{
for (int i = LeftBottom.y-; i >= LeftTop.y; i--)
{
arr[i][LeftTop.x]=Number++;
}
LeftTop.x=++LeftBottom.x;
state=;
continue;
}
} std::cout<<endl; //输出
for(int x=;x<width;x++)
{
for(int y=;y<width;y++)
{
std::cout<<setw()<<arr[x][y];
}
std::cout<<endl<<endl;
}
std::cout<<endl<<endl;
goto loop;
return ;
}
05-11 13:04