#include
#include
#define SIZE 5
#define RIGHT 1
#define DOWN 2
#define LEFT 3
#define UP 4
void printArray1(int b[SIZE][SIZE], int size);
void printArray2(int b[SIZE][SIZE], int size);
int move(int b[SIZE][SIZE], int *xpos, int *ypos, int *movem, int number);
int main(void) {
int i, j, num;
int dir;
int a[SIZE][SIZE] = { 0 };
printArray1(a, SIZE);
printf("\n\n");
printArray2(a, SIZE);
dir = RIGHT;
i = 0;
j = 0;
num = 1;
for (; num <= (SIZE * SIZE); num++ )
move(a, &i, &j, &dir, num);
printArray1(a, SIZE);
printf("\n\n");
printArray2(a, SIZE);
return 0;
}
void printArray1 (int b[SIZE][SIZE], int size)
{
int i, j;
for ( i = 0; i < size; i++ ) {
for ( j = 0; j < size; j++ )
printf("%3d ", b[j][i]);
printf("\n");
}
printf("\n\n");
return;
}
void printArray2 (int b[SIZE][SIZE], int size)
{
int i, j;
for ( i = 0; i < size; i++ ) {
for ( j = 0; j < size; j++ )
printf("%3d ", b[i][j]);
printf("\n");
}
printf("\n\n");
return;
}
int move(int b[SIZE][SIZE], int *xpos, int *ypos, int *movem, int number)
{
int x, y, dirn, reqdDirn;
x = *xpos;
y = *ypos;
dirn = *movem;
if (b[x][y] == 0 ) {
b[x][y] = number;
}
reqdDirn = dirn;
switch (dirn) {
default:
printf("Unexpected value");
return;
case RIGHT:
x = x + 1;
if (b[x][y] == 0) {
if (x > SIZE-1) {
reqdDirn = DOWN;
x = SIZE - 1;
y = y + 1;
if (y > SIZE-1)
y = SIZE - 1;
}
} else {
// just step back and change direction
x = x - 1;
y = y + 1;
reqdDirn = DOWN;
}
break;
case DOWN:
y = y + 1;
if (b[x][y] == 0) {
if (y > SIZE-1) {
reqdDirn = LEFT;
y = SIZE - 1;
x = x - 1;
if (x < 0)
x = 0;
}
} else {
y = y - 1;
x = x - 1;
reqdDirn = LEFT;
}
break;
case LEFT:
x = x - 1;
if (b[x][y] == 0) {
if (x < 0) {
reqdDirn = UP;
x = 0;
y = y - 1;
if (y < 0)
y = 0;
}
} else {
// just step back and change direction
x = x + 1;
y = y - 1;
reqdDirn = UP;
}
break;
case UP:
y = y - 1;
if (b[x][y] == 0) {
if (y < 0) {
reqdDirn = RIGHT;
y = 0;
x = x + 1;
if (x > SIZE-1)
x = SIZE - 1;
}
} else {
// just step back and change direction
y = y + 1;
x = x + 1;
reqdDirn = RIGHT;
}
break;
}
*xpos = x;
*ypos = y;
*movem = reqdDirn;
}
Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9