c++实现螺旋矩阵

螺旋矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大,向左变大,向上变大,如此循环。如下图所示:
                                                

此类题目经常出现在各大互联网公司的面试笔试这种,今天我用c++实现输入一个整N,就打印出N*N的螺旋矩阵,源码如下:
#include <iostream>
#include<iomanip>
#include<vector>
using namespace std;

int main()
{
	int n = 0;
	cout << "please input a number n:";
	while (cin >> n && n != EOF)
	{
		// 动态开辟二维数组
		vector<vector<int> > a(n + 1, vector<int>(n + 1));
		/*//申请空间
		int **a = new int*[n];
		for (int i = 0; i < n + 1; i++)
		{
		a[i] = new int[n+1];
		}
		for (i = 1; i <= n; ++i)//初始化二维数组为零
		{
		for (j = i; j <= n ; ++j)
		a[i][j] = 0;
		}*/
		int i = 0;
		int  j = 0;
		int  k = 1;
		for (i = 1; i <= n / 2; ++i)
		{
			for (j = i; j <= n - i; ++j) /* 左侧 */
			{
				a[i][j] = k++;
			}

			for (j = i; j <= n - i; ++j) /* 下方 */
			{
				a[j][n + 1 - i] = k++;
			}

			for (j = n - i + 1; j >= i + 1; j = j - 1) /* 右侧 */
			{
				a[n + 1 - i][j] = k++;
			}

			for (j = n - i + 1; j >= i + 1; j = j - 1) /* 上方 */
			{
				a[j][i] = k++;
			}
		}
		if (n != 1)
		{
			for (i = 1; i <= n; ++i)
			{
				for (j = 1; j <= n; ++j)
				{
					cout << setw(5) << a[i][j]; 
				}
				cout << endl;
			}
		}
		else
		{
			cout << setw(5) << n;
		}
		cout << endl << "please input a number n:";
		/* //释放空间
		for (int i = 0; i < n+1; i++)
		delete[]a[i];
		a = NULL;*/
	}
	return 0;
}
运行结果   :
                                                  

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LfSeanDragon/article/details/79955420
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭