poj 3984迷宫问题,属于BFS算法应用求最短路径问题。
迷宫问题
题目
定义一个二维数组:
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求最短路径,将母节点逆序输出即可。
源码:
//poj3984 迷宫问题.cpp
#include<iostream>
#include<queue>
#include<string.h> // memset
#include<stdio.h>
#define MAX 5
using namespace std;
//四个方向 (x,y)
int dir[][2]={ {0,1},{1,0},{0,-1},{-1,0} } ;
typedef struct
{
int x, y; //坐标
//int val; //值
}Node;
int map[MAX][MAX];
bool visit[MAX][MAX] ; //颜色标记 ==true 说明该节点已被访问过
Node mother[MAX][MAX]; //母亲节点
int dis[MAX][MAX]; //距离
int check(Node& Vx) //检验该点是否为有效点
{
if(Vx.x>=0 && Vx.x<5 && Vx.y>=0 && Vx.y<5 && map[Vx.x][Vx.y]==0) return true; //验证该点坐标 与 值 是否有效
else return false;
}
// Vs:start point
// Vd:end point
int Bfs(Node &Vs,Node& Vd)
{
queue<Node> Q;
Node Vn,Vw; //Vn:当前节点; Vw:临近节点
int i;
//初始状态将起点 加入队列
Q.push(Vs);
visit[Vs.x][Vs.y]=true;//设置该节点已被访问过
// mother[Vs.x][Vs.y]=NIL;
dis[Vs.x][Vs.y]=0; //初始距离为0
while( !Q.empty() )
{
//取出队列的头
Vn=Q.front();
Q.pop();
for(i=0;i<4;i++) //四个方向的 邻接点
{
Vw.x=Vn.x+dir[i][0] ;
Vw.y=Vn.y+dir[i][1] ;//计算相邻节点
if(Vw.x==Vd.x && Vw.y==Vd.y) //找到终点了
{
//把路径记录下来,需根据情况添加代码
mother[Vw.x][Vw.y]=Vn;
dis[Vw.x][Vw.y]=dis[Vn.x][Vn.y]+1;
int distance=dis[Vw.x][Vw.y]; //9-1 =5+5-1-1
//新增 将母结点存储
Node temp[distance];
Node mother_temp=Vw;
for(int k=0;k< distance-1 ;k++) //注意下标
{
temp[k]=mother[mother_temp.x][mother_temp.y];
mother_temp=mother[mother_temp.x][mother_temp.y];
}
//逆序输出母结点
for(int m=distance-2;m>=0;m--) //6-0
{
cout<<"("<<temp[m].x<<", "<<temp[m].y<<")"<<endl;
}
return true;
}
if(check(Vw) && !visit[Vw.x][Vw.y]) //Vw使一个合法的节点并且为白色
{
Q.push(Vw); //加入队列
visit[Vw.x][Vw.y] =true;//设置节点颜色
mother[Vw.x][Vw.y]=Vn; //父辈节点
dis[Vw.x][Vw.y]=dis[Vn.x][Vn.y]+1;
}
}
}
return false; //无解,此无通路
}
int main()
{
Node start,end;
start.x=0;
start.y=0;
end.x=4;
end.y=4;
memset(visit,0,sizeof(visit));
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>map[i][j];
cout<<"(0, 0)"<<endl;
Bfs(start,end);
cout<<"(4, 4)"<<endl;
return 0;
}
——————————————-
END
————————————-