迷宫问题的解决-栈的应用
声明和栈的声明一样:
#include "stdio.h" #include "stdlib.h" typedef struct { int x,y,d; } DataType; struct SeqStack { int MAXNUM; //t<MAXNUM,指示栈顶位置,而不是元素个数; int t; DataType *s; }; //顺序栈类型的指针类型 typedef struct SeqStack * PSeqStack; //创建空栈 PSeqStack createEmptyStack_seq(int m) { PSeqStack pStack=(PSeqStack)malloc(sizeof(struct SeqStack)); if (pStack!=NULL) { pStack->s=(DataType *)malloc(sizeof(DataType) * m); if(pStack->s) { pStack->MAXNUM=m; pStack->t=-1; return pStack; } else { free(pStack); } } printf("out of space!! \n"); return NULL; } //判断pStack是否为空栈,如果是,则返回1,否则返回0; int isEmptyStack_seq(PSeqStack pStack) { return (pStack->t==-1); } //进栈操作 void push_seq(PSeqStack pStack,DataType x) { if (pStack->t>=pStack->MAXNUM-1) { printf("overflow! \n"); } else { pStack->t=pStack->t+1; pStack->s[pStack->t]=x; } } //出栈操作 void pop_seq(PSeqStack pStack) { if (pStack->t==-1) { printf("Underflow! \n"); } else { pStack->t=pStack->t-1; } } //取栈顶元素 DataType top_seq(PSeqStack pStack) { if (pStack->t==-1) { printf("empty ! \n"); } else { return (pStack->s[pStack->t]); } }
迷宫的算法:
//迷宫maze[M][N]中求从入口maze[x1][y1]到出口maze[x2][y2]的一条路径,其中 //1<=x1,x2<=M-2,1<=y1,y2<=N-2 //走过的点maze[g][h]==2; void mazePath(int *maze[],int *direction[],int x1,int y1,int x2,int y2,int M,int N) { int i,j,k; int g,h; PSeqStack st; DataType element; st=createEmptyStack_seq(M*N); //从入口开始进入,做标记 maze[x1][y1]=2; element.x=x1; element.y=y1; element.d=-1; //从入口点进栈; push_seq(st,element); //走不通时,一步步回退 while (!isEmptyStack_seq(st)) { element=top_seq(st); pop_seq(st); i=element.x; j=element.y; k=element.d+1; //依次试探每个方向 while (k<=3) { g=i+direction[k][0]; h=j+direction[k][1]; if (g==x2 && h==y2 && maze[g][h]==0) { //打印路径上的没一点; printf("The revers path is :\n"); while (!isEmptyStack_seq(st)) { element=top_seq(st); pop_seq(st); printf("the node is: %d %d \n",element.x,element.y); } return; } //走到没走过的点 if (maze[g][h]==0) { //做标记 maze[g][h]=2; element.x=i; element.y=j; element.d=k; push_seq(st,element); //下一个点转换成当前点 i=g; j=h; k=-1; } k=k+1; } } printf("The path has not been found . \n"); }
测试:
int main() { int i,j; int direction[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; int maze[8][11]={{1,1,1,1,1,1,1,1,1,1,1},{1,0,1,0,0,1,1,1,0,0,1},{1,0,0,0,0,0,1,0,0,1,1}, {1,0,1,1,1,0,0,0,1,1,1},{1,0,0,0,1,0,1,1,0,1,1},{1,1,0,0,1,0,1,1,0,0,1}, {1,1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1,1}}; int *ap[4]; for(i=0;i<4;i++) { ap[i]=direction[i]; } int *aq[11]; for(i=0;i<11;i++) { aq[i]=maze[i]; } mazePath(aq,ap,1,1,6,9,8,11); return 1; }
结果: