1.data.h
# ifndef _DATA_H
# define _DATA_H
typedef struct
{
int y;
int x;
}POS;
typedef struct
{
int sno;
POS seat;
int di;
}ElemType;
# endif
2.stack.h
# ifndef _STACK_H
# define _STACK_H
# include "data.h"
# define STACK_INIT_SIZE 10
# define STACK_INCREME 10
typedef struct
{
ElemType * base;
ElemType * top;
int size;
}STACK;
int Pop(STACK * s, ElemType * e);
int Push(STACK * s, ElemType * e);
void DestroyStack(STACK * s);
STACK * InitStack();
int IsEmpty(STACK * s);
# endif
3.stack.c
# include "stack.h"
# include <stdio.h>
# include <stdlib.h>
STACK * InitStack()
{
STACK * s = (STACK *)malloc(sizeof(STACK));
if(NULL == s)
exit(0);
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(NULL == s->base) exit(0);
s->top = s->base;
s->size = STACK_INIT_SIZE;
return s;
}
void DestroyStack(STACK * s)
{
free(s->base);
free(s);
}
int Push(STACK * s, ElemType * e)
{
if(s == NULL || e == NULL)
return 0;
if(s->top - s->base >= s->size)
{
s->base = (ElemType *)realloc(s->base, (s->size +
STACK_INCREME) * sizeof(ElemType));
if(s->base == NULL) return 0;
s->top = s->base + s->size;
s->size = s->size + STACK_INCREME;
}
* s->top ++ = * e;
return 1;
}
int Pop(STACK * s, ElemType * e)
{
if(s == NULL || e == NULL)
return 0;
if(s->base == s->top)
return 0;
* e = * --s->top;
return 1;
}
int IsEmpty(STACK * s)
{
return s->top == s->base ? 1 : 0;
}
4.main.c
# include "stack.h"
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
int item[10][10] = {
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1, 0, 1},
{1, 0, 0, 0, 0, 1, 1, 0, 0, 1},
{1, 0, 1, 1, 1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 1, 0, 0, 0, 1, 0, 0, 1},
{1, 0, 1, 1, 1, 0, 1, 1, 0, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
};
static const POS inPos = {1, 1}, outPos = {8, 8};
int IsPass(POS curP)
{
return item[curP.y][curP.x] == 0 ? 1 : 0;
}
POS NextPos(POS curP, int di)
{
POS p = curP;
switch(di)
{
case 0:
p.x--;
break;
case 1:
p.y++;
break;
case 2:
p.x++;
break;
case 3:
p.y--;
break;
default: break;
}
return p;
}
void PrintItem(POS curP)
{
int i, j;
system("cls");
for(i=0; i<10; ++i)
{
for(j=0; j<10; ++j)
{
if(i == curP.y && j == curP.x)
{
printf("@");
continue;
}
if(item[i][j] == 1)
printf("*");
else
printf(" ");
}
printf("\n");
}
}
void main()
{
ElemType e;
int setp = 1;
POS curPos = inPos;
STACK * s = InitStack();
PrintItem(inPos);
getch();
do
{
if(IsPass(curPos))
{
e.sno = setp;
e.di = 0;
e.seat = curPos;
Push(s, &e);
item[curPos.y][curPos.x] = 2;
if(curPos.y == outPos.y && curPos.x == outPos.x)
{
PrintItem(curPos);
printf("OK\n");
break;
}
PrintItem(curPos);
getch();
curPos = NextPos(curPos, 0);
setp++;
}else
{
Pop(s, &e);
if(e.di == 4 && !IsEmpty(s))
{
item[curPos.y][curPos.x] = 3;
Pop(s, &e);
}
if(e.di < 3)
{
e.di ++;
Push(s, &e);
curPos = NextPos(e.seat, e.di);
}
}
}while(!IsEmpty(s));
}