//烟台大学 计算机学院 软件工程 王朝#include <stdio.h>#define MaxSize 100#define M 8#define N 8int mg[M+2][N+2]={ {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}};typedef struct{ int i;//定义行 int j;//定义列 int di;//下一个要走的方块的位置} Box;typedef struct{ Box data[MaxSize];//行列和存储下个位置的数组 int top;//栈顶指针} StType;int mgpath(int xi,int yi,int xe,int ye){ int i,j,di,k,find; StType st;//定义栈 st.top=-1;//初始化栈顶指针 st.top++;//进栈 st.data[st.top].i=xi;//入口 st.data[st.top].j=yi;//入口 st.data[st.top].di=-1;//初始化位置*1 mg[xi][yi]=-1;//表示该位置是否可走 while(st.top>-1)//栈不为空时循环 { i=st.data[st.top].i;//下三行为方块的位置和要走的下个方块状态 j=st.data[st.top].j; di=st.data[st.top].di; if(i==xe&&j==ye) { printf("迷宫路径如下:\n"); for(k=0; k<=st.top; k++) { printf("\t(%d,%d)",st.data[k].i,st.data[k].j); if((k+1)%5==0) printf("\n"); } printf("\n"); return (1); } find=0;//某个条件进行的条件,以某个状态表示 while(di<4&&find==0) { di++; switch(di) { case 0: i=st.data[st.top].i-1; j=st.data[st.top].j; break; case 1: i=st.data[st.top].i; j=st.data[st.top].j+1; break; case 2: i=st.data[st.top].i+1; j=st.data[st.top].j; break; case 3: i=st.data[st.top].i; j=st.data[st.top].j-1; break; } if(mg[i][j]==0) find=1; } if(find==1)//如果走通继续循环 { st.data[st.top].di=di; st.top++; st.data[st.top].i=i;//记录位置 st.data[st.top].j=j; st.data[st.top].di=-1;//新的方块回归原始状态 mg[i][j]=-1;//避免重复走这个方块 } else { mg[st.data[st.top].i][st.data[st.top].j]=0;//走不通将状态置为0 st.top--;//回溯 } } return (0);}int main(){ mgpath(1,1,M,N); return 0;}//只记录可以走通的位置走不通后会消去
0 0