#include <stdio.h>int main(){ int a[10][10]; int i,j,k,n,b=0; scanf("%d",&n); for ( i=0; i<n/2; i++) { for ( j=i; j<n-i; j++) /*四个循环按不同的方向进行*/ a[i][j] = ++b; for ( k=i+1,j--; k<n-i; k++ ) a[k][j] = ++b; for ( j=--k,j--; j>=i; j-- ) a[k][j] = ++b; for ( k--;
k>i; k-- ) a[k][i] = ++b; } if ( n%2 ) /*如果是单数的话,要加上最大的那个数放在中间*/ a[i][i] = ++b; for ( i=0; i<n; i++) { for ( j=0; j<n; j++) printf("%3d",a[i][j]); printf("\n"); } fflush(stdin); getchar(); return 0;}
方法一:
方法2:
#define MAX 100
#define RIGHT 0
#define LEFT 1
#define UP 2
#define DOWN 3
typedef struct Position
{
int x;
int y;
}Pos;
int guid[MAX][MAX] = {0};
int map[MAX][MAX];
Pos CurPos;
int LastDirection;
int n;
int GetDirection();
void GetNextPos(int Direction);
void Show();
int main()
{
scanf("%d", &n);
CurPos.x = CurPos.y = 0;
map[0][0] = 1;
guid[0][0] = 1;
LastDirection = RIGHT;
for(int k = 0; k < n * n - 1; k++)
{
int Direction = GetDirection();
GetNextPos(Direction);
map[CurPos.x][CurPos.y] = k + 2;
guid[CurPos.x][CurPos.y] = 1;
LastDirection = Direction;
}
Show();
fflush(stdin);
getchar();
return 0;
}
int GetDirection()
{
if(LastDirection == RIGHT)
{
if(CurPos.y == n - 1 || guid[CurPos.x][CurPos.y + 1] == 1)
return DOWN;
else
return RIGHT;
}
else
if(LastDirection == DOWN)
{
if(CurPos.x == n - 1 || guid[CurPos.x + 1][CurPos.y] == 1)
return LEFT;
else
return DOWN;
}
else
if(LastDirection == LEFT)
{
if(CurPos.y == 0 || guid[CurPos.x][CurPos.y - 1] == 1)
return UP;
else
return LEFT;
}
else
if(LastDirection == UP)
{
if(CurPos.x == 0 || guid[CurPos.x - 1][CurPos.y] == 1)
return RIGHT;
else
return UP;
}
}
void GetNextPos(int Direction)
{
switch(Direction)
{
case RIGHT:
CurPos.y++;
break;
case DOWN:
CurPos.x++;
break;
case LEFT:
CurPos.y--;
break;
case UP:
CurPos.x--;
break;
}
}
void Show()
{
for(int m = 0; m < n; m++)
{
for(int k = 0; k < n; k++)
{
printf("%4d", map[m][k]);
}
printf("\n");
}
}