0

考虑一个数组

0000
0000
0000

然后在数组中一个完全随机的位置生成一个数

0000
0000
00x0

我想要做的是知道数字的位置,让它以螺旋顺序通过数组。我在 c++ 中找不到东西,这是我唯一知道的语言。

我已经知道如何以螺旋顺序从元素 [0][0] 到 [1][2](顺时针),但是如果我的初始位置是随机的,我该怎么做?那么,我该如何逆时针逆时针?依此类推,但应该从那个随机位置开始(随机生成的 2 个数字将是位置)。

4

1 回答 1

1

仅当您指向数组的中心时,此代码才有效。如果您添加正确的边界检查,这应该如您所描述的那样工作。我做了假设(基于您的第一个示例),当您完成所有现有元素时,您将移动到外部集合。IE

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 ++;
}
}
于 2013-11-12T19:18:33.567 回答