POJ 3984 - 迷宫问题 - [BFS水题]

时间:2022-11-23 18:42:38

题目链接:http://poj.org/problem?id=3984

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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

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

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

题解:

裸的BFS水题。

AC代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
const int dx[]={,,,-};
const int dy[]={,,-,}; int mp[][];
struct Node{
int x,y;
int cnt;
Node(){}
Node(int _x,int _y,int _cnt) {
x=_x, y=_y, cnt=_cnt;
}
inline bool out() {
return x< || x>= || y< || y>=;
}
};
queue<Node> Q;
bool vis[][];
Node pre[][];
stack<Node> ans; int main()
{
memset(mp,,sizeof(mp));
for(int i=;i<;i++) for(int j=;j<;j++) scanf("%d",&mp[i][j]); memset(vis,,sizeof(vis));
Q.push((Node){,,});
vis[][]=;
while(!Q.empty())
{
Node now=Q.front(); Q.pop();
if(now.x== && now.y==)
{
ans.push(now);
break;
}
for(int k=;k<;k++)
{
Node nxt=Node(now.x+dx[k],now.y+dy[k],now.cnt+);
if(nxt.out()) continue;
if(mp[nxt.x][nxt.y]) continue;
if(vis[nxt.x][nxt.y]) continue;
Q.push(nxt);
vis[nxt.x][nxt.y]=;
pre[nxt.x][nxt.y]=now;
}
} while(ans.top().cnt) ans.push(pre[ans.top().x][ans.top().y]);
while(!ans.empty())
{
printf("(%d, %d)\n",ans.top().x,ans.top().y);
ans.pop();
}
}