#include"fstream"
#include<string>
#include<iostream>
using namespace std;
#define MAXSIZE 100
#define m 8
#define n 8
int maze[m+2][n+2];
栈的表示
typedef struct
{
int i,j,di;
}Box;
typedef struct
{
Box data[MAXSIZE];
int top;
}StType;
迷宫函数
void MazePath(int xi,int yi,int xe,int ye)
{
int i=0,j=0,a=1,k,di,find;
StType s;
s.top=-1;
s.top++;
s.data[s.top].i=xi;//栈顶元素
s.data[s.top].j=yi;
s.data[s.top].di=-1;
maze[xi][yi]=-1;
while(s.top>-1)
{
i=s.data[s.top].i;//取栈顶元素
j=s.data[s.top].j;
di=s.data[s.top].di;
if(i==xe&&j==ye)
{getchar();
cout<<"找到第"<<a++<<"个出口:\n";getchar();
for(k=0;k<=s.top;k++)
{cout<<"("<<s.data[k].i<<","<<s.data[k].j<<")";
if((k+1)%5==0)cout<<endl;
}
cout<<endl;
}
find=0;
while(di<4&&find==0)
{
di++;
switch(di)
{
case 0:
i=s.data[s.top].i-1;//向左
j=s.data[s.top].j;
break;
case 1:
i=s.data[s.top].i; //向上
j=s.data[s.top].j+1;
break;
case 2:
i=s.data[s.top].i+1;//向右
j=s.data[s.top].j;
break;
case 3:
i=s.data[s.top].i;
j=s.data[s.top].j-1;//向下
break;
}
if(maze[i][j]==0) find=1;
}
if(find==1)
{
s.data[s.top].di=di;
s.top++;
s.data[s.top].i=i;
s.data[s.top].j=j;
s.data[s.top].di=-1;
maze[i][j]=-1;
}
else
{
maze[s.data[s.top].i][s.data[s.top].j]=0;
s.top--;
}
}
}
从.txt文件中读取迷宫(迷宫以存放在此文件中)
例如
1 1 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 0 1 1 1 1 1 1 1 1
1 0 0 1 1 1 1 1 1 1
1 0 0 1 1 1 1 1 1 1
1 1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1
void file(const char *filename,int a[m+2][n+2])
{
ifstream infile(filename,ios::in);
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0;i<m+2;i++)
for(int j=0;j<n+2;j++)
{ infile>>a[i][j];
}
infile.close();
}
主函数
int main()
{
int t=0;
string fn;
cout<<"输入存放迷宫的文件地址(.txt文件):";
cin>>fn;
file(fn.c_str(),maze);
cout<<"迷宫:\n";
for(int i=0;i<m+2;i++)
for(int j=0;j<n+2;j++)
{
if(maze[i][j]==1)cout<<"■";
else cout<<"□";
t++;
if(t%10==0) cout<<endl;
}
getchar();
MazePath(1,1,m,n);
system("pause");
return 0;
}