2017-09-28 20:46:06
writer:pprp
题意:
迷宫是一个二维矩阵,其中1为墙,0为路,3为入口,4为出口.要求从入口开始,从出口结束,按照 下,左,上,右 的顺序来搜索路径.
分析:
采用bfs的方法,如果将所有能找到最终终点的路径都压栈,进行存储
代码如下:
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
struct node
{
int a, b;
friend ostream& operator<<(ostream& os,const node& n)
{
os << n.b << " " << n.a << endl;
return os;
}
};
stack<node> sk;
int s1,s2,e1,e2;
int w, h;
const int mx = 10000;
int mp[mx][mx];
bool vis[mx][mx];
int dx[] = {1,0,-1,0};
int dy[] = {0,-1,0,1};
bool check(int a, int b)
{
if(a >= 1 && a <= h &&
b >= 1 && b <= h && vis[a][b] == 0)
{
if(mp[a][b] == 0||mp[a][b] == 4)
return 1;
}
return 0;
}
bool seekPath(int x,int y)
{
if(x == e1 && y == e2)
return 1;
for(int i = 0 ; i < 4; i++)
{
int tx = x + dx[i], ty = y + dy[i];
if(check(tx,ty))
{
vis[tx][ty] = 1;
if(seekPath(tx,ty))
{
node *newnode = new node;
newnode->a = tx;
newnode->b = ty;
sk.push(*newnode);
return 1;
}
vis[tx][ty] = 0;
}
}
return 0;
}
int main()
{
freopen("in.txt","r",stdin);
// cin >> w >> h;
scanf("%d%d",&w,&h);
for(int i = 0 ; i < h ; i++)
for(int j = 0 ; j < w; j++)
mp[i][j] = vis[i][j] = 0;
for(int i = 0 ; i < h ; i++)
{
for(int j = 0; j < w; j++)
{
cin >> mp[i][j];
if(mp[i][j] == 3)
s1 = i,s2 = j;
if(mp[i][j] == 4)
e1 = i,e2 = j;
}
}
vis[s1][s2] = 1;
seekPath(s1,s2);
cout << s2 << " " << s1 << endl;
while(!sk.empty())
{
cout << sk.top();
sk.pop();
}
return 0;
}