http://blog.csdn.net/u014713819/article/details/26723313
理论看这个
迷宫问题:
#include<iostream>
#include <deque>
#include <stack>
#include <vector>
using namespace std;
const int di[4] = {0,1,0,-1},
dj[4] = {1,0,-1,0};
//四组方向
/*unsigned maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0};
unsigned flag[5][5] = {0};*/ //访问标准,记录路径
typedef struct
{
int i;
int j;
int dis;
}node;
deque<node> dnode;
//根据flag数组反向查找路径
stack<node> getpath(vector<vector<int> >& f,int x,int y,int d,int pos2x,int pos2y)
{
node first,last;
stack<node> ret;
first.i = pos2x;
first.j = pos2y;
first.dis = d;
ret.push(first);
while(first.dis != 1)
{
for(int i=0;i<4;++i)
{
if(first.i+di[i]>=0 &&first.i+di[i]<x
&& first.j+dj[i]>=0 &&first.j+dj[i]<y
&& f[first.i+di[i]][first.j+dj[i]]==(first.dis-1))
{
last.i = first.i+di[i];
last.j = first.j+dj[i];
last.dis = first.dis-1;
ret.push(last);
first = last;
}
}
}
return ret;
}
int main(void)
{
//维度
int x,y;
cin>>x>>y;
vector<vector<int> > maze;
vector<int> mazetemp;
int temp;
//输入maze
for (int i=0;i<x;++i)
{
for(int j=0;j<y;++j)
{
cin>>temp;
mazetemp.push_back(temp);
}
maze.push_back(mazetemp);
mazetemp.clear();
}
//访问记录
vector<vector<int> > flag;
for (int i=0;i<x;++i)
{
for(int j=0;j<y;++j)
{
mazetemp.push_back(0);
}
flag.push_back(mazetemp);
mazetemp.clear();
}
//起始和终止位置
int pos1x,pos1y,pos2x,pos2y;
cin>>pos1x>>pos1y>>pos2x>>pos2y;
node first,last;
first.i = pos1x;
first.j = pos1y;
first.dis = 0;
dnode.push_back(first);
while(!dnode.empty()) //bfs
{
first = dnode.front();
dnode.pop_front();
flag[pos1x][pos1y]=1;
for(int i=0;i<4;++i)
{
if(first.i+di[i]>=0 &&first.i+di[i]<x
&& first.j+dj[i]>=0 &&first.j+dj[i]<y
&& maze[first.i+di[i]][first.j+dj[i]]==0
&& flag[first.i+di[i]][first.j+dj[i]]==0)
{
last.i = first.i+di[i];
last.j = first.j+dj[i];
last.dis = first.dis+1;
flag[last.i][last.j] = last.dis+1;
dnode.push_back(last);
if(last.i==pos2x &&last.j==pos2y)
{
cout<<"have path"<<endl;
stack<node> ret = getpath(flag,x,y,last.dis+1,pos2x,pos2y);
while(!ret.empty())
{
cout<<'('<<ret.top().i<<','<<ret.top().j<<')'<<"->";
ret.pop();
}
return 0;
}
}
}
}
printf("No path.\n");
return 0;
}