數組的螺旋式打印

/*
問題描述:給定一個2維數組,將數組中的元素以螺旋狀順序打印出來
來源:網易算法課
日期:2017-10-23

*/

#include <iostream>
using namespace std;

class ArraySpiral{
public:
	ArraySpiral(int n)
	{
		arr = new int *[n];
		for (int i = 0; i < n; i++)
			arr[i] = new int[n];

		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				arr[i][j] = i*n + j + 1;
			}
		}

		top = 0;
		right = n - 1;
		bottom = n - 1;
		left = 0;
	}

	void printArray()
	{
		while (top <= bottom && left <= right)
		{
			for (int i = left; i <= right; i++)
			{
				cout << arr[top][i] << " ";
			}
			for (int i = top + 1; i <= bottom; i++)
			{
				cout << arr[i][right] << " ";
			}
			for (int i = right - 1; i >= left; i--)
			{
				cout << arr[bottom][i] << " ";
			}
			for (int i = bottom - 1; i > top; i--)
			{
				cout << arr[i][left] << " ";
			}

			top++;
			right--;
			left++;
			bottom--;

		}
	}
private:
	int **arr;
	int top = 0, right = 0, bottom = 0, left = 0;
};

/*
int main()
{
	ArraySpiral as(4);
	as.printArray();

	return 0;
}
*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章