このコードは、ポイントが配列の中心にある場合にのみ機能します。正しい境界チェックを追加すると、これは説明どおりに機能するはずです。(最初の例に基づいて)既存のすべての要素を終了すると、外側のセットに移動すると仮定しました。すなわち
0000
0000
00x0
になる
2222
2111
21x1
この順番で触る
6 7 8 9
11 1 2 3
10 5 X 4
2 は 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 ++;
}
}