最近开始潜心学习算法,从基础开始吧。加油!!
这是螺旋数组的实现,可以选择顺时针、逆时针,升序、降序(即从里到外或者从外到里)。
/**
螺旋数组
*/
class SpiralArray
{
public:
enum DIRECTION{CW,ACW}; //CW顺时针clockwise,ACW逆时针anticlockwise
enum OEDER{AO,DO}; //从外往里走,AO升序ascending order,降序descending order
SpiralArray(const int _N,const DIRECTION _d = CW,const OEDER _o = AO);
~SpiralArray();
friend std::ostream& operator <<(std::ostream& out,const SpiralArray& array);
private:
void construct();
private:
int **array;
int N;
DIRECTION d;
OEDER o;
};
SpiralArray::SpiralArray(const int _N,const DIRECTION _d,const OEDER _o)
:N(_N),d(_d),o(_o)
{
assert(N > 0);
array = new int*[N];
for(int i=0;i<N;++i)
array[i] = new int[N];
construct();
}
SpiralArray::~SpiralArray()
{
for(int i=0;i<N;++i)
if(array[i] != NULL) delete[] array[i];
delete[] array;
}
/**
构造螺旋数组
*/
void SpiralArray::construct()
{
if(o == AO) //升序
{
int m=1,i,j,k;
if(d == CW) //顺时针
{
for(k=0;k<N/2;++k) //需要填的圈数,N/2圈
{
i = k;
for(j=k;j<N-k;++j)
array[i][j]=m++; //横
j = N-k-1;
for(i=k+1;i<N-k;++i)
array[i][j]=m++; //列
i = N-k-1;
for(j=N-k-2;j>=k;--j)
array[i][j]=m++; //逆横
j = k;
for(i=N-k-2;i>=k+1;--i)
array[i][j]=m++; //逆列
}
if(N%2 == 1)array[N/2][N/2]=m;
}
else if(d == ACW) //逆时针
{
for(k=0;k<N/2;++k) //需要填的圈数,N/2圈
{
j = k;
for(i=k;i<N-k;++i)
array[i][j]=m++; //列
i = N-k-1;
for(j=k+1;j<N-k;++j)
array[i][j]=m++; //横
j = N-k-1;
for(i=N-k-2;i>=k;--i)
array[i][j]=m++; //逆列
i = k;
for(j=N-k-2;j>=k+1;--j)
array[i][j]=m++; //逆横
}
if(N%2 == 1)array[N/2][N/2]=m;
}
}
else if(o == DO) //降序
{
int m=N*N,i,j,k;
if(d == CW) //顺时针
{
for(k=0;k<N/2;++k) //需要填的圈数,N/2圈
{
i = k;
for(j=k;j<N-k;++j)
array[i][j]=m--; //横
j = N-k-1;
for(i=k+1;i<N-k;++i)
array[i][j]=m--; //列
i = N-k-1;
for(j=N-k-2;j>=k;--j)
array[i][j]=m--; //逆横
j = k;
for(i=N-k-2;i>=k+1;--i)
array[i][j]=m--; //逆列
}
if(N%2 == 1)array[N/2][N/2]=m;
}
else if(d == ACW) //逆时针
{
for(k=0;k<N/2;++k) //需要填的圈数,N/2圈
{
j = k;
for(i=k;i<N-k;++i)
array[i][j]=m--; //列
i = N-k-1;
for(j=k+1;j<N-k;++j)
array[i][j]=m--; //横
j = N-k-1;
for(i=N-k-2;i>=k;--i)
array[i][j]=m--; //逆列
i = k;
for(j=N-k-2;j>=k+1;--j)
array[i][j]=m--; //逆横
}
if(N%2 == 1)array[N/2][N/2]=m;
}
}
}
std::ostream& operator <<(std::ostream& out,const SpiralArray& sa)
{
if(sa.array == NULL) return out;
for(int i=0;i<sa.N;++i)
{
for(int j=0;j<sa.N;++j)
out<<sa.array[i][j]<<"\t";
out<<endl;
}
return out;
}
//使用螺旋数组类
int main()
{
SpiralArray a(7,SpiralArray::ACW,SpiralArray::DO);
cout<<a; //输出
return EXIT_SUCCESS;
}