/*
在n*n方阵里填入1,2,3,..nxn的数,要求埴成蛇形,例如n=4的方阵为
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
*/
int m[maxn][maxn];
void SnakeFillNum()
{
int n, x, y, tot = 0;
scanf_s("%d", &n);
memset(m, 0, sizeof(a));
tot = m[x = 0][y = n - 1] = 1;
while (tot < n*n)
{
while (x + 1 < n && !m[x + 1][y]) m[++x][y] = ++tot;
while (y - 1 >= 0 && !m[x][y - 1]) m[x][--y] = ++tot;
while (x - 1 >= 0 && !m[x - 1][y])m[--x][y] = ++tot;
while (y + 1 < n && !m[x][y + 1])m[x][++y] = ++tot;
}
for (x = 0; x < n; x++)
{
for (y = 0; y < n; y++)
{
printf_s("%3d", m[x][y]);
}
printf_s("\n");
}
}
算法-蛇形数组
最新推荐文章于 2019-12-27 13:23:01 发布