以下是引用njkido在2011-3-28 14:55:53的发言:
自己写的 没什么算法 好懂
#define RIGHT__ 0
#define LEFT__
1
#define UP__
2
#define DOWN__
3
#define N 9
typedef void (*DragonArrayMoveMethodFn)(unsigned short Array[N][N],unsigned short*,unsigned short*);
void MoveDown(unsigned short Array[N][N],unsigned short *CurrentX,unsigned short *CurrentY)
{
Array[*CurrentX+1][*CurrentY] = Array[*CurrentX][*CurrentY] + 1;
(*CurrentX)++;
return;
}
void MoveUp(unsigned short Array[N][N],unsigned short *CurrentX,unsigned short *CurrentY)
{
Array[*CurrentX-1][*CurrentY] = Array[*CurrentX][*CurrentY] + 1;
(*CurrentX)--;
return;
}
void MoveLeft(unsigned short Array[N][N],unsigned short *CurrentX,unsigned short *CurrentY)
{
Array[*CurrentX][*CurrentY-1] = Array[*CurrentX][*CurrentY] + 1;
(*CurrentY)--;
return;
}
void MoveRight(unsigned short Array[N][N],unsigned short *CurrentX,unsigned short *CurrentY)
{
Array[*CurrentX][*CurrentY+1] = Array[*CurrentX][*CurrentY] + 1;
(*CurrentY)++;
return;
}
DragonArrayMoveMethodFn Move[]={
MoveRight,
MoveLeft,
MoveUp,
MoveDown
};
unsigned short GetNewAction(unsigned short LastAction)
{
//clockwise
switch (LastAction)
{
case RIGHT__:
return DOWN__;
case LEFT__:
return UP__;
case UP__:
return RIGHT__;
case DOWN__:
return LEFT__;
}
}
bool IsNeedChangeAction(unsigned short Array[N][N],unsigned short CurrentX,unsigned short CurrentY,unsigned short LastAction)
{
switch (LastAction)
{
case DOWN__:
return (CurrentX == N-1) || Array[CurrentX+1][CurrentY] != 0;
case UP__:
return (CurrentX == N-1) || Array[CurrentX-1][CurrentY] != 0;
case RIGHT__:
return (CurrentY == N-1) || Array[CurrentX][CurrentY+1] != 0;
case LEFT__:
return (CurrentY == N-1) || Array[CurrentX][CurrentY-1] != 0;
}
}
void GenDragonArray()
{
unsigned short CurrentX = 0;
unsigned short CurrentY = 0;
unsigned short DragonArray[N][N] = {0};
unsigned short CurrentAction = RIGHT__;
unsigned short Count = 0;
DragonArray[0][0] = 1;
while(Count<(N*N)-1)
{
//Determine whether need change action
if (IsNeedChangeAction(DragonArray,CurrentX,CurrentY,CurrentAction))
{
//Change Move Action
CurrentAction = GetNewAction(CurrentAction);
}
//Move
Move[CurrentAction](DragonArray,&CurrentX,&CurrentY);
Count++;
}
{
int i=0;
int j=0;
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
printf("%02d ",DragonArray[j]);
}
printf("\n");
}
}
}
结果:
01 02 03 04 05 06 07 08 09
32 33 34 35 36 37 38 39 10
31 56 57 58 59 60 61 40 11
30 55 72 73 74 75 62 41 12
29 54 71 80 81 76 63 42 13
28 53 70 79 78 77 64 43 14
27 52 69 68 67 66 65 44 15
26 51 50 49 48 47 46 45 16
25 24 23 22 21 20 19 18 17
请按任意键继续. . .