C++ 简洁打印 N阶螺旋矩阵

打印螺旋矩阵问题。


/* N阶螺旋矩阵
* author : tofu
* date : 20160405
* site : 520
*/
#include   
using namespace std;

int main()
{	
	int n, i, j, q, var;
	cout << "please input the size of matrix: ";
	while (cin >> n) {
		int **p = new int*[n];//new matrix of n * n
		for (i = 0; i < n; i++)
			p[i] = new int[n];

		var = 1;//set the initial value
		for ( q = 0; q < n / 2; q++) {//q represents the number of turns
			
			for (i = j = q; j < n - q - 1; j++)
				p[i][j] = var++;
			for (; i < n - q - 1; i++)
				p[i][j] = var++;
			for (; j > q; j--)
				p[i][j] = var++;
			for (; i > q; i--)
				p[i][j] = var++;

		}

		if (n % 2 == 1)//If n is odd, then the center number of the matrix need to handle it
			p[n / 2 ][n / 2 ] = var;

		for (i = 0; i < n; i++) {
			for (j = 0; j < n; j++)
				cout << p[i][j] << " ";
			cout << endl;
		}

		for (i = 0; i < n; i++)
			delete[] p[i];
		delete[] p;

		cout << "please input the size of matrix: ";
	}
	return 0;
}


C++ 简洁打印 N阶螺旋矩阵_第1张图片

C++ 简洁打印 N阶螺旋矩阵_第2张图片

你可能感兴趣的:(C++ 简洁打印 N阶螺旋矩阵)