以下是代码,麻烦大神看一下有没有错
输入:n = 4;
结果:14 15 16 1
0 0 0 2
0 0 0 3
7 6 5 4
#include <iostream>
#include <iomanip>
#define maxn 20
using namespace std;
int str[maxn][maxn];
int main()
{
cout << "输入方阵:";
int n;
cin >> n;
int x = 0, y = n - 1, tot = 1;
memset(str, 0, sizeof(str));
str[0][n - 1] = 1;
while (tot < n * n)
{
while (x+1< n && str[x+1][y] == 0)
str[++x][y] = ++tot;//down move
while (y+1>= 0 && str[x][y-1] == 0)
str[x][--y] = ++tot;//left move
while (x - 1 >= 0 && str[x - 1][y] == 0)
str[--x][y] = ++tot;//up move
while (y + 1 < n && str[x][y + 1] == 0)
str[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
cout << setw(5) << str[x][y];
cout << endl;
}
system("pause");
return 0;
}