1255:迷宫问题
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 7919 通过数: 3656
【题目描述】
定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
【输入】
一个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
【输出样例】
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
【分析】
这是典型的迷宫问题。用bfs实现,需要注意的事,广搜到出口结点,一定存在着一条路径通到出口,并且输出走过的路径,需要递归输出所走路径。
【参考代码】
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
struct node
{
int x;
int y;
}q[35][35]; //记录走过的路径
int dir[][2]={{1,0},{-1,0},{0,1},{0,-1}}; //方向数组
int vis[5][5]; //访问数组
int maze[5][5]; //迷宫地图
void print(int x, int y) //递归输出路径
{
if(x==-1 && y==-1)
return;
print(q[x][y].x,q[x][y].y);
printf("(%d, %d)\n",x,y);
}
void bfs()
{
vis[0][0]=-1;
q[0][0].x=-1;
q[0][0].y=-1;
queue <node> r; //申请队列
node s;
s.x=0;
s.y=0;
vis[0][0]=1;
r.push(s); //起点入队
while(!r.empty())
{
node t,tmp;
t=r.front();
if(t.x==4 && t.y==4) //到达终点
{
print(4,4);
}
for(int i=0;i<4;i++)
{
int nx=t.x+dir[i][0];
int ny=t.y+dir[i][1];
if(nx>=0 && nx<5 && ny>=0 && ny<5 && (!vis[nx][ny]) && !(maze[nx][ny]))
{
vis[nx][ny] = 1;
tmp.x=nx;
tmp.y=ny;
r.push(tmp);
q[nx][ny].x=t.x;
q[nx][ny].y=t.y;
}
}
r.pop();
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d", &maze[i][j]);
bfs();
return 0;
}