- 论坛徽章:
- 0
|
改进了一下
void clockwisematrixfill (int n)
{
enum
{ NDIRECTIONS = 4 };
int directions[NDIRECTIONS][4] = {
{1, 0, 1, 4}, {0, 1, 5, 4}, {-1, 0, -1, 0}, {0, -1, -5, 0}
};
int (*pd)[4];
int coor[2];
int *ai, *pa;
int i, nn, directionidx = 0;
nn = n * n;
ai = (int *) calloc (nn, sizeof (int));
pd = directions;
(*pd)[2] = 1; (*pd)[3] = n - 1; pd++;
(*pd)[2] = n; (*pd)[3] = n - 1; pd++;
(*pd)[2] = -1; (*pd)[3] = 0; pd++;
(*pd)[2] = -n; (*pd)[3] = 0;
coor[0] = coor[1] = 0;
pa = ai;
pd = directions;
for (i = 1; i <= nn; i++)
{
*pa = i;
if (coor[directionidx % 2] == (*pd)[3] || *(pa + (*pd)[2]) != 0)
{
directionidx++;
pd++;
if (directionidx >= NDIRECTIONS)
{
directionidx = 0;
pd = directions;
}
}
coor[0] += (*pd)[0];
coor[1] += (*pd)[1];
pa += (*pd)[2];
}
for (i = 0, pa = ai; i < nn; i++, pa++)
{
if ((i + 1) % n)
printf ("%.2d ", *pa);
else
printf ("%.2d\n", *pa);
}
printf ("\n");
free (ai);
} |
|