#include#include #define N 100 typedef struct{ int row,col,dir; }locate; typedef struct{ int horiz,vert; }offsets; int Top=-1; /* 初始堆疊頂端 */ locate Stack[N]; offsets move[4]={ [0]={ .horiz=0, .vert=-1}, //N [1]={ .horiz=1, .vert=0}, //E [2]={ .horiz=0, .vert=1}, //S [3]={ .horiz=-1, .vert=0} //W }; void Push(locate); locate Pop(); void PrintStack(); int main() { int mrows,mcols,exitrow,exitcol,i,j,row,col,dir=0; locate position; scanf("%d %d",&mrows,&mcols); /* Input maze size m*n */ scanf("%d %d",&exitrow,&exitcol); /* Input exitrow exitcol */ int maze[mrows+2][mcols+2]; int mark[mrows+2][mcols+2]; /* Record Visited position in mark array */ for(i=0;i<mrows+2;i++) /* Initial maze and mark array */ { for(j=0;j<mcols+2;j++) { mark[i][j]=0; /* Initial mark array to 0 */ if(i==0 || i==mrows+1 || j==0 || j==mcols+1) /* if row=0 or row=last row col=0 or col=last col set maze[i][j]=1 be wall */ maze[i][j]=1; else scanf("%d",&maze[i][j]); /* else input maze data*/ } } printf("\n===== 顯示迷宮 =====\n"); for(i=0;i<mrows+2;i++) { for(j=0;j<mcols+2;j++) { if(maze[i][j]==1) printf("█"); else printf(" "); } printf("\n"); } //printf("\n"); int entr_ROW=1,entr_COL=1; /* Set maze entraence(1,1) */ int next_ROW,next_COL; /* next position */ Top=0; /* push entrance to Stack */ Stack[0].row=entr_ROW; Stack[0].col=entr_COL; Stack[0].dir=dir; mark[entr_ROW][entr_COL]=1; //PrintStack(); while(Top > -1) { position=Pop(); /* pop position from Stack */ row=position.row; col=position.col; dir=position.dir; //printf("%d %d %d\n",row,col,dir); while(dir<4) { next_ROW=row+move[dir].vert; next_COL=col+move[dir].horiz; //printf("%d %d %d",next_ROW,next_COL,dir);//break; if(next_ROW==exitrow && next_COL==exitcol) { //mark[next_ROW][next_COL]=1; position.row=row; position.col=col; position.dir=dir; Push(position); printf("\n===== 顯示迷宮路徑 =====\n"); for(i=Top;i>=0;i--) { maze[Stack[i].row][Stack[i].col]=3; //printf("%d %d %d\n",Stack[i].row,Stack[i].col,Stack[i].dir); } for(i=0;i<mrows+2;i++) { for(j=0;j<mcols+2;j++) { if(maze[i][j]==0) printf(" "); else if(maze[i][j]==1) printf("█"); else printf("○"); } printf("\n"); } return 0; } else if(maze[next_ROW][next_COL]==0 && mark[next_ROW][next_COL]==0) { mark[next_ROW][next_COL]=1; position.row=row; position.col=col; position.dir=dir; Push(position); /* Save the current position */ row=next_ROW; /* Specify the next position */ col=next_COL; dir=0; /* Zero the direction */ } else dir++; } } printf("迷宮沒有出口!\n"); return 0; } void Push(locate item) { if(Top==(N-1)) { printf("= Stack full ! =\n"); } else { //Top=Top+1; Stack[++Top]=item; } } locate Pop() { if(Top==-1) { printf("= Stack empty ! =\n"); } else { return Stack[Top--]; } } void PrintStack() { int i; if(Top==-1) { printf("堆疊是空的!\n"); } else { printf("= Stack contain : =\n"); for(i=Top;i>=0;i--) printf("%d %d %d\n",Stack[i].row,Stack[i].col,Stack[i].dir); printf("\n"); } }
2017年12月10日
老鼠走迷宮
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。