/******************************
作者:cncoderalex
博客:http://blog.youkuaiyun.com/cncoderalex
*******************************/
#include <iostream>
#include <memory>
#include <string>
#include <algorithm>
using namespace std;
#define MAXN 20
int Ary[MAXN][MAXN];
void FillSnakeSquare(int n)
{
int total = 1;
int x = 0, y = n - 1;
memset(Ary, 0, sizeof(Ary));
Ary[x][y] = 1;
while (total < n * n)
{
while (x < n - 1 && !Ary[x + 1][y]) Ary[++x][y] = ++total;
while (y > 0 && !Ary[x][y - 1]) Ary[x][--y] = ++total;
while (x > 0 && !Ary[x - 1][y]) Ary[--x][y] = ++total;
while (y < n - 1 && !Ary[x][y + 1]) Ary[x][++y] = ++total;
}
}
void PrintAry(int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%3d", Ary[i][j]);
}
printf("\n");
}
}
int main()
{
printf("http://blog.youkuaiyun.com/cncoderalex");
printf("\n");
int n;
while (scanf("%d", &n) != EOF)
{
FillSnakeSquare(n);
PrintAry(n);
}
system("pause");
return 0;
}
蛇形填数
最新推荐文章于 2024-10-25 18:55:54 发布