您的位置:首页 > 其它

螺旋矩阵-【无聊模拟】

2011-12-30 14:14 267 查看
#include <stdio.h>

#define Max_Size        256
#define INITIAL_CH        0
#define Value_Start        1

typedef enum {
Dir_Center = 0,
Dir_Left,
Dir_Bottom,
Dir_Right,
Dir_Top,
Dir_Max
};

int Map[Max_Size][Max_Size];

/*
0,0------------->iy
|
|
|
|
^ix
iSize is the array size,
iDirect is current Direct.

he will return the next usefull direct.
*/
int reDirect(int *ix, int *iy, int iSize, int iDirect) {
int reDirectValue = Dir_Center;    //Next Direct
int iFullDirectChange = 1;            //Check the Full Direct
while (iFullDirectChange && iFullDirectChange < Dir_Max) {
switch (iDirect)
{
case Dir_Left:
/* TODO : Current Direct is left,
Check the Left is not out of array.
and Test the the map value is not used.
then still use the current direct, change the current index.
otherwise change the next direct. */
if ((*iy - 1) >= 0 && Map[*ix][*iy - 1] == INITIAL_CH) {    //Left
*iy -= 1;
reDirectValue = Dir_Left;
iFullDirectChange = 0;
} else {
reDirectValue = Dir_Bottom;
iFullDirectChange++;
}
break;
case Dir_Bottom:
if ((*ix + 1) < iSize && Map[*ix + 1][*iy] == INITIAL_CH) {    // bottom
*ix += 1;
reDirectValue = Dir_Bottom;
iFullDirectChange = 0;
} else {
reDirectValue = Dir_Right;
iFullDirectChange++;
}
break;
case Dir_Right:
if ((*iy + 1) < iSize && Map[*ix][*iy + 1] == INITIAL_CH) {    //Right
*iy += 1;
reDirectValue = Dir_Right;
iFullDirectChange = 0;
} else {
reDirectValue = Dir_Top;
iFullDirectChange++;
}
break;
case Dir_Top:
if ((*ix - 1) >= 0 && Map[*ix - 1][*iy] == INITIAL_CH) {    //Top
*ix -= 1;
reDirectValue = Dir_Top;
iFullDirectChange = 0;
} else {
reDirectValue = Dir_Left;
iFullDirectChange++;
}
break;
default: printf("Error!\n"); iFullDirectChange = 0; break;
}

iDirect = reDirectValue;
}

return iFullDirectChange == Dir_Max ? Dir_Center : reDirectValue;
}

/*
use this function to initial the array.
*/
void initial(int iValue, int iSize) {
int ix = 0, iy = 0;
int CurDirect = Dir_Left;
for (ix = 0; ix < iSize; ix++) {
for (iy = 0; iy < iSize; iy++) {
Map[ix][iy] = INITIAL_CH;
}
}

for ( ix = 0, iy = 0; Dir_Center != CurDirect; CurDirect = reDirect(&ix, &iy, iSize, CurDirect) ) {
Map[ix][iy] = iValue++;
}
}

/*
use this function to show array value.
*/
void DrawArray(int iSize) {
int ix = 0, iy = 0;
for (ix = 0; ix < iSize; ix++) {
for (iy = 0; iy < iSize; iy++) {
printf( "%d ", Map[ix][iy]);
}
printf( "\n");
}
}

int main() {

int iValue = Value_Start;
int iSize = 4;

initial(iValue, iSize);
DrawArray(iSize);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redirect function include