c++实现螺旋矩阵

#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;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120