假如输入2,那么蛇形填数为
4 1
3 2
输入3的话,即
7 8 1
6 9 2
5 4 3
现输入n,输出它的蛇形填数
#include<iostream>
#include<string.h>//use memset
#include<iomanip>//use setw
using namespace std;
int main()
{
int a[20][20];
int n;
while (cin >> n)
{
memset(a, 0, sizeof(a));
int count = 1;
int x = -1;
int y = n - 1;
while (count <= n*n)
{//先判断能不能做,然后再去决定
while (x + 1 < n && a[x + 1][y] == 0) a[++x][y] = count++;
while (y - 1 > -1 && a[x][y - 1] == 0) a[x][--y] = count++;
while (x - 1 >-1 && a[x - 1][y] == 0) a[--x][y] = count++;
while (y + 1 < n && a[x][y + 1] == 0) a[x][++y] = count++;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
cout << left << setw(3) << a[x][y];
cout << ((y == n - 1) ? "\n" : " ");
}
}
}
return 0;
}