(简单) POJ 3984 迷宫问题,BFS。

时间:2023-03-09 03:20:03
(简单)  POJ  3984  迷宫问题,BFS。

  Description

  定义一个二维数组:
int 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,

};

  它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

  水题,BFS然后记录路径就好。
代码如下:
#include<iostream>
#include<cstring>
#include<queue>
#include<utility> using namespace std; typedef struct pair<int,int> pii; int vis[][];
int fa[][]; bool judge(int x,int y)
{
if(x<||y<||x>||y>)
return ; if(vis[x][y])
return ; return ;
} void slove()
{
queue < pii > que;
pii temp,temp1;
int t1,t2; que.push(make_pair(,));
vis[][]=; while(!que.empty())
{
temp=que.front();
que.pop(); t1=temp.first/;
t2=temp.first%;
fa[t1][t2]=temp.second; if(t1==&&t2==)
return; --t1;
if(judge(t1,t2))
{
vis[t1][t2]=;
temp1=make_pair(t1*+t2,temp.first);
que.push(temp1);
}
t1+=;
if(judge(t1,t2))
{
vis[t1][t2]=;
que.push(make_pair(t1*+t2,temp.first));
}
--t1;
--t2;
if(judge(t1,t2))
{
vis[t1][t2]=;
que.push(make_pair(t1*+t2,temp.first));
}
t2+=;
if(judge(t1,t2))
{
vis[t1][t2]=;
que.push(make_pair(t1*+t2,temp.first));
}
}
} void showans()
{
int cou=;
int ans[];
int temp=; while(temp)
{
ans[cou++]=temp;
temp=fa[temp/][temp%];
} cout<<"(0, 0)"<<endl;
for(int i=cou-;i>=;--i)
cout<<'('<<ans[i]/<<", "<<ans[i]%<<')'<<endl;
} int main()
{
ios::sync_with_stdio(false); while(cin>>vis[][])
{
for(int j=;j<;++j)
cin>>vis[][j]; for(int i=;i<;++i)
for(int j=;j<;++j)
cin>>vis[i][j]; slove();
showans();
} return ;
}