C++《走迷宫案例》能否给下源代码?
C++《走迷宫案例》能否给下源代码?
C++《走迷宫案例》能否给下源代码?
2015-06-26
#include<iostream>
using namespace std;
/************************************/
/*Get Maze from OutFile*/
void Maze_GetFile(int maze[][20])
{
int i,j;
freopen("E:\\Text_Maze.txt","r",stdin);
for(i=0;i<10;i++)
for(j=0;j<20;j++)
cin>>maze[i][j];
fclose(stdin);
}
/************************************/
/* function of the Stack of maze */
typedef struct ST_maze{
int a;
int b;
int dir;
struct ST_maze *next;
}ST_maze, *LinkStack;
/************************************/
bool InitStack(LinkStack &S)
{
S=NULL;
return true;
}
/************************************/
void Free_Stack(LinkStack &S)
{
LinkStack p;
while(S!=NULL)
{
p=S;S=S->next;
free(p);
}
}
/************************************/
LinkStack Push(LinkStack &S,ST_maze e)
{
LinkStack p=new ST_maze;
if(!p)
exit(0);
p->a=e.a;
p->b=e.b;
p->dir=e.dir;
p->next=S;
S=p;
return S;
}
/************************************/
LinkStack Pop(LinkStack &S,ST_maze &e)
{
if(S==NULL)
return NULL;
LinkStack p=S;
e.a=S->a;
e.b=S->b;
e.dir=S->dir;
S=S->next;
free(p);
return S;
}
/************************************/
bool StackEmpty(LinkStack &S)
{
if(S==NULL)
return true;
else
return false;
}
/************************************/
int movei[4] = {0, 1, 0, -1};
int movej[4] = {1, 0, -1, 0};
void NextPos(int &i,int &j,int turn)
{
i = i + movei[turn-1];
j = j + movej[turn-1];
}
/************************************/
int Maze_Data(int turn)
{
switch(turn)
{
case 1:return 2;
case 2:return 3;
case 3:return 4;
case 4:return 5;
default:return -1;
}
}
/***********************************/
LinkStack Maze_path(LinkStack &ST,int Maze[][20])
{
InitStack(ST);
ST_maze e;
int i=1;int j=0;int curstep=1;
e.a=1;e.b=0;e.dir=1;
do
{
if(Maze[i][j]==0)
{
Maze[e.a][e.b]=Maze_Data(e.dir);
e.a=i;e.b=j;e.dir=1;e.next=NULL;
Push(ST,e);
if(i==8&&j==19)
{
Maze[8][19]=2;
return ST;
}
NextPos(i,j,1);
curstep++;
}//endif
else
{
if(!StackEmpty(ST))
{
Pop(ST,e);
while(e.dir==4&&!StackEmpty(ST))
{
i=e.a;j=e.b;
Maze[i][j]=-1;
Pop(ST,e);
}//endwhile
if(e.dir<4)
{
e.dir++;
Push(ST,e);
i=e.a;j=e.b;
NextPos(i,j,e.dir);
}//endif
}//endif
}//endelse
}while(!StackEmpty(ST));
return NULL;
}
/***********************************/
void Maze_Output(int Maze[][20])
{
int i,j;
for(i= 0;i<10;i++)
{
for( j =0;j<20;j++)
{
switch(Maze[i][j]){
case -1:case 0: cout<<" ";break;
case 1: cout<<"■";break;
case 2: cout<<"→";break;
case 3: cout<<"↓";break;
case 4: cout<<"←";break;
case 5: cout<<"↑";break;
default:break;
}
}
cout<<endl;
}
}
/***********************************/
void main(void)
{
int Maze[10][20];LinkStack ST;
Maze_GetFile(Maze);
cout<<"the Original Maze:"<<endl;
Maze_Output(Maze);
cout<<" One Way For the Maze:"<<endl;
Maze_path(ST,Maze);
Maze_Output(Maze);
}
举报