#include <stdio.h>
#define SIZE 1024
struct Box
{
int x;
int y;
int dir;
};
typedef struct Box Box;
typedef struct
{
Box data[SIZE];
int top;
}Stack;
int map[6][6] = {
{0, 0, 0, 1, 0, 1},
{0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0},
{0, 1, 0, 1, 1, 0},
{0, 1, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0}};
int InitStack(Stack *s)
{
if (!s)
return -1;
s->top = -1;
return 0;
}
int check(Box b)
{
if (b.x < 0 || b.x > 5 || b.y < 0 || b.y > 5)
return -1;
if (map[b.x][b.y] != 0)
return -1;
return 1;
}
int push(Stack *s, Box b)
{
if (s->top == SIZE - 1 || !s)
return -1;
s->top++;
s->data[s->top] = b;
return 0;
}
int EmptyStack(Stack *s)
{
if (!s)
return -1;
return (s->top == -1) ? 1 : 0;
}
int GetTop(Stack *s, Box *b)
{
if (!s || s->top == -1)
return -1;
*b = s->data[s->top];
return 0;
}
void ShowPath(Stack *s)
{
int i;
for (i = 0; i <= s->top; i++)
{
printf("(%d %d)", s->data[i].x, s->data[i].y);
if (i != s->top)
{
printf("->");
}
}
printf("\n");
}
int pop(Stack *s, Box *b)
{
if (!s || s->top == -1)
return -1;
*b = s->data[s->top];
s->top--;
return 0;
}
int ChangeDir(Stack *s, int dir)
{
if (!s || s->top == -1)
return -1;
s->data[s->top].dir = dir;
return 0;
}
int Walk(Stack *s, int x1, int y1, int x2, int y2)
{
Box now, t;
int i, j;
now.x = x1;
now.y = y1;
now.dir = -1;
if (check(now) == 1)
{
push(s, now);
map[now.x][now.y] = -1;
}
while (EmptyStack(s) != 1)
{
GetTop(s, &now);
if (now.x == x2 && now.y == y2)
{
ShowPath(s);
map[now.x][now.y] = 0;
pop(s, &now);
GetTop(s, &now);
}
else
{
int k;
for (k = now.dir + 1; k < 4; k++)
{
switch(k)
{
case 0:
i = now.x - 1;
j = now.y;
break;
case 1:
i = now.x;
j = now.y + 1;
break;
case 2:
i = now.x + 1;
j = now.y;
break;
case 3:
i = now.x;
j = now.y - 1;
break;
}
t.x = i;
t.y = j;
t.dir = -1;
if (check(t) == 1)
{
ChangeDir(s, k);
push(s, t);
map[i][j] = -1;
break;
}
}
if (k == 4)
{
pop(s, &now);
map[now.x][now.y] = 0;
}
}
}
}
int main()
{
Stack stack;
InitStack(&stack);
Walk(&stack, 0, 0, 5, 5);
return 0;
}