怎么不使用数组编译一个这样的螺旋方阵?
设计目标:输入一个数n,输出一个n*n的螺旋方阵:eg:输入:5
输出:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
程序代码:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main(void)
{
int n = 0;
cin >> n;
vector<vector<int>> ivec(n ,vector<int>(n, 0));
int dir = 1;
int x = 0;
int y = 0;
int i = 1;
for (i = 1; i <= n*n;)
{
switch (dir)
{
case 1:
for (;y != n; ++y)
{
if (ivec[x][y] != 0)
break;
ivec[x][y] = i++;
// cout << "(" << x << ", " << y << ") = " << i-1 << endl;
}
--y;
++x;
++dir;
break;
case 2:
for (;x != n; ++x)
{
if (ivec[x][y] != 0)
break;
ivec[x][y] = i++;
// cout << "(" << x << ", " << y << ") = " << i-1 << endl;
}
--x;
--y;
++dir;
break;
case 3:
for (;y >= 0; --y)
{
if (ivec[x][y] != 0)
break;
ivec[x][y] = i++;
// cout << "(" << x << ", " << y << ") = " << i-1 << endl;
}
++y;
--x;
++dir;
break;
case 4:
for (;x >= 0; --x)
{
if (ivec[x][y] != 0)
break;
ivec[x][y] = i++;
// cout << "(" << x << ", " << y << ") = " << i-1 << endl;
}
++x;
++y;
dir = 1;
break;
default:
break;
}
}
for (x = 0; x != n; ++x)
{
for (y = 0; y != n; ++y)
cout << ivec[x][y] << "\t";
cout << endl;
}
return 0;
}