输入正整数n,要求打印出n*n的蛇形方阵。如n=4时打印如下:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int a[10][10];
int main()
{
int top, bottom, left, right, n;
int num = 1;
int i, j;
scanf("%d", &n);
top = 0;
bottom = n-1;
left = 0;
right = n-1;
a[0][n-1] = num;
i = 0;
j = n-1;
while (num < n*n)
{
while (i < bottom)
{
a[++i][j] = ++num;
}
right--;
while (j > left)
{
a[i][--j] = ++num;
}
bottom--;
while (i > top)
{
a[--i][j] = ++num;
}
left++;
while (j < right)
{
a[i][++j] = ++num;
}
top++;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%3d ", a[i][j]);
}
printf("\n");
}
return 0;
}
版权声明:本文为brucehb原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。