[c++]代码库
void SpiralMatrix(int height, int width, int startNum, int startPos)
{
int** martix = new int* [height];
for (int i=0; i<height; i++)
{
*(martix+i) = new int[width];
}
int loop = 0;
int totalCnt = height*width;
if (height == 2 || width == 2)
{
loop = 2;
}
else
{
int heightLoop = height/2 + 1;
int widthLoop = width/2 + 1;
loop = heightLoop<width?heightLoop:widthLoop;
}
int x = 0, y=0;
for (int round=0; round<loop; round++)
{
int widthEnd = width - 1 - round;
int heightEnd = height - 1 - round;
for (x=round; x<=widthEnd; x++)
{
*(*(martix+round)+x) = startNum++;
}
for (y=round+1; y<=heightEnd; y++)
{
*(*(martix+y)+widthEnd) = startNum++;
}
if (startNum > totalCnt)
{
break;
}
for (x=widthEnd-1; x>=round; x--)
{
*(*(martix+heightEnd)+x) = startNum++;
}
for (y=heightEnd-1; y>round; y--)
{
*(*(martix+y)+round) = startNum++;
}
}
for (y=0; y<height; y++)
{
for (x=0; x<width; x++)
{
cout<<*(*(martix+y)+x)<<" ";
}
cout<<endl;
}
}
by: 发表于:2015-07-10 12:02:29 顶(0) | 踩(0) 回复
不明觉厉!石荣峰 http://shirongfeng.com/
回复评论