Skip to content

Instantly share code, notes, and snippets.

@aweimeow
Created October 20, 2014 03:36
Show Gist options
  • Save aweimeow/0195d8e377c244489452 to your computer and use it in GitHub Desktop.
Save aweimeow/0195d8e377c244489452 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 100
typedef struct{
short int vert;
short int horiz;
}offsets;
offsets move[8];
typedef struct{
short int row;
short int col;
short int dir;
}element;
element stack[MAX_STACK_SIZE];
int top =1;
short int maze[180]={
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,
},max_row=15,max_col=12,arrive=0;
void stackFull(){
printf( "堆疊已滿,不能再加入元素");
exit(EXIT_FAILURE);
}
void push(element item){
if(top>=MAX_STACK_SIZE -1)
stackFull();
stack [++top] = item;
}
element pop(){
if(top==-1){
printf("堆疊是空的");
}
return stack[top--];
}
void path(void){
int i,j,row,col,nextRow,nextCol,dir,found = false;element position;
int EXIT_ROW=15,EXIT_COL=12;
for (i=0;i<max_col;i++)
{
for (j=0;j<max_row;j++)
{
if(maze[j+(i*max_row)]!=0){
printf("%c",'*');
}else printf("0");
}
printf("\n");
}
maze[0]=1; top =0;
move[1].vert=-1;
move[1].horiz=0;
move[2].vert=-1;
move[2].horiz=1;
move[3].vert=0;
move[3].horiz=1;
move[4].vert=1;
move[4].horiz=1;
move[5].vert=1;
move[5].horiz=0;
move[6].vert=1;
move[6].horiz=-1;
move[7].vert=0;
move[7].horiz=-1;
move[8].vert=-1;
move[8].horiz=-1;
stack[0].row = 1; stack[0].col = 1;stack[0].dir=1;
do{
position = pop();
row = position.row; col = position.col;
dir = position.dir;
while(dir <8 && !found){
nextRow = row +move[dir].horiz;
nextCol = col +move[dir].vert;
if(nextRow ==EXIT_ROW && nextCol ==EXIT_COL)
found = true;
else if ( !maze[nextRow*max_row+nextCol] ){
maze[row*max_row+col]=1;
position.row=row;position.col=col;
position.dir=dir;
push(position);
row = nextRow;
col = nextCol;
dir=1;
}else ++dir;
}
}while(top >-1 && !found);
if(found){
printf("The path is : \n");
printf("row col\n");
for(i=0;i<=top;i++)
printf("%2d%5d\n",stack[i].row, stack[i].col);
//printf("%2d%5d\n",row,col);
printf("%2d%5d\n",EXIT_ROW,EXIT_COL);
}
else printf("The maze does not have a path\n");
return ;
}
int main(){
printf("走迷宮\n");
path();
system("PAUSE");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment