仅当您的点位于数组的中心时,此代码才有效。如果您添加正确的边界检查,这应该如您所描述的那样工作。我做了一个假设(基于您的第一个示例),当您完成所有现有元素时,您将移动到外部集合。即
0000
0000
00x0
变成
2222
2111
21x1
按此顺序触摸它们
6 7 8 9
11 1 2 3
10 5 X 4
用2代表第二个圆圈,1代表第一个圆圈。
这个程序的输出是(我只是在每个元素中存储了“半径”)
pre traversal
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
post traversal
2 2 2 2 2
2 1 1 1 2
2 1 0 1 2
2 1 1 1 2
2 2 2 2 2
// what is the maximum possible radius
int getMaxRadius(int x, int y, int size)
{
int toReturn = std::abs(size-x);
if(std::abs(size-y) > toReturn)
toReturn = std::abs(size -y);
return toReturn ;
}
//is the curernt element next to the current center
bool nextTo(int xCenter, int yCenter, int x, int y, int radius )
{
//if it
if(std::abs(xCenter - x) > radius || std::abs(yCenter - y) > radius)
{
return false;
}
return true;
}
void circular(int** array, int xCenter, int yCenter, int size)
{
int curRadius = 1;
int maxRadius = getMaxRadius(xCenter, yCenter,size);
while( curRadius<maxRadius)
{
//start to the top left of the cur radius
int curX = xCenter - curRadius;
int curY = yCenter - curRadius;
//go right
while(nextTo(xCenter, yCenter, curX, curY, curRadius ))
{
array[curX][curY] = curRadius;
curX ++;
}
curX--;//we went one too far
//go down
while(nextTo(xCenter, yCenter, curX, curY, curRadius ))
{
array[curX][curY] = curRadius;
curY ++;
}
curY--;//we went one too far
//go left
while(nextTo(xCenter, yCenter, curX, curY, curRadius ))
{
array[curX][curY] = curRadius;
curX --;
}
curX++;//we went one too far
//goUP
while(nextTo(xCenter, yCenter, curX, curY, curRadius ))
{
array[curX][curY] = curRadius;
curY --;
}
curY++;//we went one too far
curRadius ++;
}
}