#include <stdio.h>
#include <stdlib.h>
//#define SElemType int
#define INIT_SIZE 10
#define INCRE_SIZE 10
#define MAXLENGTH 10
//坐标
typedef struct{
int x;
int y;
}PosType;
//封装的类型
typedef struct{
int ord;
PosType seat;
int di;
}SElemType;
typedef struct{
SElemType *top;
SElemType *base;
int stackSize;
}SqStack;
void InitStack(SqStack &S){
S.base = S.top = (SElemType *)malloc(sizeof(SElemType)*INIT_SIZE);
if(!S.base){
exit(-1);
}
S.stackSize = INIT_SIZE;
}
void Push(SqStack &S,SElemType e){
if(S.top - S.base >= S.stackSize){
S.base = (SElemType*)realloc(S.base,sizeof(SElemType)*(INCRE_SIZE+S.stackSize));
if(!S.base){
exit(-1);
}
S.top = S.base + S.stackSize;
S.stackSize += INCRE_SIZE;
}
*S.top++ = e;
}
void Pop(SqStack &S,SElemType &e){
if(S.top != S.base){
e = *(--S.top);
}
}
int StackEmpty(SqStack S){
if(S.top == S.base){
return 1;
}else{
return 0;
}
}
/*void Print(SqStack S){
while(!StackEmpty(S)){
SElemType e;
Pop(S,e);
// printf("%d ",e);
}
}*/
//全局变量
//typedef int MazeType[MAXLENGTH][MAXLENGTH];
int m[10][10] = {
{0,0,0,0,0,0,0,0,0,0},
{0,1,1,0,1,1,1,0,1,0},
{0,1,1,0,1,1,1,0,1,0},
{0,1,1,1,1,0,0,1,1,0},
{0,1,0,0,0,1,1,1,1,0},
{0,1,1,1,0,1,1,1,1,0},
{0,1,0,1,1,1,0,1,1,0},
{0,1,0,0,0,1,0,0,1,0},
{0,0,1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0,0,0},
};
/*int m[8][8]={{0,0,0,0,0,0,0,0},
{0,0,1,0,0,1,0,0},{0,1,1,0,0,0,1,0},
{0,1,0,0,0,0,0,0},{0,1,1,1,0,0,1,0},{0,0,0,1,0,0,1,0},
{0,0,0,1,1,1,1,0},{0,0,0,0,0,0,0,0}};*/
int curstep = 1;
int Pass(PosType pos){
if(m[pos.x][pos.y]==1){
return 1;
}else{
return 0;
}
}
void FootPrint(PosType pos){
m[pos.x][pos.y] = -2;
}
PosType NextPos(PosType pos,int di){
PosType d[5] = {{0,0},{0,1},{1,0},{0,-1},{-1,0}};
pos.x += d[di].x;
pos.y += d[di].y;
return pos;
}
void MarkPrint(PosType pos){
m[pos.x][pos.y] = -1;
}
int MazeSearch(PosType start,PosType end){
SqStack S;
SElemType e;
InitStack(S);
PosType curpos = start;
curstep = 1;
do{
if(Pass(curpos)){
FootPrint(curpos);
e.ord = curstep;
e.seat.x = curpos.x;
e.seat.y = curpos.y;
e.di = 1;
Push(S,e);
if(curpos.x == end.x && curpos.y == end.y){
return 1;
}
curpos = NextPos(curpos,e.di);
curstep++;
}else{
if(!StackEmpty(S)){
Pop(S,e);
// curstep--;
while(e.di==4&&!StackEmpty(S)){
MarkPrint(e.seat);
Pop(S,e);
printf("No:%d--%d\n",e.seat.x,e.seat.y);
// curstep--;
}//while
if(e.di<4){
e.di++;
Push(S,e);
printf("Yes:%d--%d\n",e.seat.x,e.seat.y);
// curstep++;
curpos = NextPos(curpos,e.di);
}//if
}//if
}//else
}while(!StackEmpty(S));
return 0;
}
void PrintMaze(int x,int y){ // 输出迷宫的解
int i,j;
for(i=0;i<x;i++){
for(j=0;j<y;j++){
printf("%3d",m[i][j]);
}
printf("\n");
}
}
int main(){
PosType start,end;
start.x = 1;
start.y = 1;
end.x = 8;
end.y = 8;
MazeSearch(start,end);
PrintMaze(10,10);
return 0;
}
06-26
296
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交