螺旋数组

螺旋数组,是将N*N数组如下设置

3*3

123
894
765
4*4

1234
1213145
1116156
10987
5*5

12345
161718196
152425207
142322218
131211109
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;
}

点赞