螺旋数组,是将N*N数组如下设置
4*41 | 2 | 3 | 4 |
12 | 13 | 14 | 5 |
11 | 16 | 15 | 6 |
10 | 9 | 8 | 7 |
5*51 | 2 | 3 | 4 | 5 |
16 | 17 | 18 | 19 | 6 |
15 | 24 | 25 | 20 | 7 |
14 | 23 | 22 | 21 | 8 |
13 | 12 | 11 | 10 | 9 |
class HelixLine
{
public:
enum Direction
{
RIGHT,
DOWN,
LEFT,
UP,
};
HelixLine(unsigned int);
~HelixLine();
void draw();
void show();
private:
unsigned int m_nSize;
unsigned int* m_map;
};
HelixLine::HelixLine(unsigned int size):
m_nSize(size),
m_map(NULL)
{
}
HelixLine::~HelixLine()
{
if (NULL!= m_map)
{
delete[] m_map;
m_map = NULL;
}
}
void HelixLine::draw()
{
if(NULL == m_map)
{
m_map = new unsigned int[m_nSize * m_nSize];
}
int x = 0;
int y = 0;
//四周边界,每次到达拐点,当前边界向中心靠拢
int xLeft = -1;
int xRight = m_nSize;
int yTop = 0;
int yBottom = m_nSize;
//数组值产生器
int count = 0;
//方向标志
Direction d = RIGHT;
while(count < m_nSize * m_nSize)
{
m_map[y * m_nSize + x] = ++count;
switch(d)
{
case RIGHT:
if (x + 1 == xRight)
{
d = DOWN;
++y;
--xRight;
}
else
{
++x;
}
break;
case DOWN:
if (y + 1 == yBottom)
{
d = LEFT;
--x;
--yBottom;
}
else
{
++y;
}
break;
case LEFT:
if (x -1 == xLeft)
{
d = UP;
--y;
++xLeft;
}
else
{
--x;
}
break;
case UP:
if (y - 1 == yTop)
{
d = RIGHT;
++x;
++yTop;
}
else
{
--y;
}
}
}
}
void HelixLine::show()
{
for(int i = 0; i < m_nSize * m_nSize; ++i)
{
if (i % m_nSize == 0)
{
cout << endl;
/* code */
}
cout << m_map[i] << '\t';
}
cout << endl;
}