1111111111
0111111111
0110000000
0101110000
0111010000
0000011000
0000111000
0000010110
0000001111
0000000001
1:类似于这种迷宫,1代表 可以通过,0代表不可以通过
2:本程序只是针对从(0,0)为入口,最后一个为出口的情况
3:本程序迷宫的输入文件名为“1.txt”,按实际情况需改动代码
4:程序执行的时候将原来的迷宫进行了“加边”,方便处理
//:maze.cpp
#include<iostream>
#include<vector>
#include<stack>
#include<fstream>
using namespace std;
struct Location{
int x;
int y;
Location(int j=0,int k=0){x=j;y=k;}
};
void get_maze(vector<vector<bool> >&);
void getout(const vector<vector<bool> >&,vector<Location>&);
void show(vector<Location>&);
int main()
{
vector<vector<bool> >maze;
get_maze(maze);
// cout<<"get_maze()-----OK"<<endl;
//输出maze
typedef vector<vector<bool> >::iterator VVB;
typedef vector<bool>::iterator VB;
for(VVB vvi=maze.begin();vvi!=maze.end();++vvi)
{
for(VB vi=vvi->begin();vi!=vvi->end();++vi)
{
cout<<*vi<<' ';
}
cout<<endl;
}
vector<Location> way;
getout(maze,way);
// cout<<"getout()------OK"<<endl;
show(way);
system("pause");
}
/
void get_maze(vector<vector<bool> >&maze)
{
// cout<<"Input the maze (10X10) : "<<endl;
//输入文件名为“1.txt”,按实际情况需改动代码
ifstream fin("1.txt");
for(int i=0;i!=12;++i)
{
vector<bool> temp;
if(i==0||i==11) for(int i=0;i!=12;++i)temp.push_back(0);
else{
temp.push_back(0);
for(int j=0;j!=10;++j)
{
char m;
fin>>m;
if(m=='1') temp.push_back(true);
else
temp.push_back(false);
}
temp.push_back(0);
}
maze.push_back(temp);
}
}
/
void getout(const vector<vector<bool> >&maze,vector<Location>&way)
{
//加边后从(1,1)开始,即原来迷宫的(0,0)
if(maze[1][1]==0) { cout<<"入口错误!"<<endl; return; }
vector<vector<bool> >state(maze);
int j=1,k=1;
stack<Location> ls;
for(int i=0;i!=121;++i)
{
// cout<<'.'<<"/t"<<endl;
ls.push(Location(j,k));
if(j==10&&k==10) break;
if(state[j][k+1]) { ++k;}//temp.push(Location(j,k+1));
else if(state[j+1][k]){ ++j;}
else if(state[j][k-1]) { --k;}
else if(state[j-1][k]) { --j;}
else{
ls.pop();
if(ls.empty()){
Location mm=ls.top();
j=mm.x;k=mm.y;
}
}
state[j][k]=0;
}
vector<Location> temp;
while( ! ls.empty() ) { temp.push_back(ls.top());ls.pop();}
// cout<<"loop------OK"<<endl;
for(vector<Location>::iterator iter=temp.end()-1;iter!=temp.begin()-1; --iter)
way.push_back(*iter);
}
///
void show(vector<Location>&way)
{
if( way.empty() ) { cout<<"没有出路!"<<endl; return; }
cout<<"路径为:"<<endl;
for(vector<Location>::iterator iter=way.begin();iter!=way.end();++iter)
cout<<iter->x<<" , "<<iter->y<<endl;
}
//: Powered by Gu
//: ^_^