POJ 3984 迷宫问题 BFS
来源:互联网 发布:js幻灯片特效代码 编辑:程序博客网 时间:2024/06/06 04:21
迷宫问题
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 16315 Accepted: 9743
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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 00 1 0 1 00 0 0 0 00 1 1 1 00 0 0 1 0
Sample Output
(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4)
Source
题意:基础的BFS题目,在求取最短路径的基础上需要打印路径。
分析:基本的BFS模板,加上一个递归打印路径。在此将5*5迷宫中的每个点编序,其号码为5*x+y,x和y为横纵坐标。建立pre数组记录每个点的前一个点,根据其下标唯一确定那个点,执行递归即可。见AC代码:
#include<stdio.h>#include<queue>using namespace std;const int maxn=6;int dirx[4]= {0,0,-1,1};int diry[4]= {-1,1,0,0};int map[maxn][maxn];int vis[maxn][maxn];int sx=0,sy=0,ex=4,ey=4;struct p{int x,y,step,pre;};int pre[30];void Print(int n){//printf("打印\n");if(n==0)return ;Print(pre[n]);printf("(%d, %d)\n",n/5,n%5);}void BFS(){queue<p> q;p p1;p1.x=sx;p1.y=sy;p1.step=0;pre[0]=-1;q.push(p1);while(!q.empty()){p f=q.front(),temp;q.pop();if(f.x==ex&&f.y==ey){//printf("%d \n",pre[24]);Print(24);//4 4 转化成24 return ;}for(int i=0; i<4; i++){temp.x=f.x+dirx[i];temp.y=f.y+diry[i];temp.step=f.step+1;if(temp.x<=4&&temp.x>=0&&temp.y<=4&&temp.y>=0&&!vis[temp.x][temp.y]&&map[temp.x][temp.y]==0){pre[temp.x*5+temp.y]=f.x*5+f.y;q.push(temp);vis[temp.x][temp.y]=1;}}}}int main(){for(int i=0; i<5; i++)for(int j=0; j<5; j++){scanf("%d",&map[i][j]);vis[i][j]=0;}printf("(0, 0)\n");BFS();}多刷题,长见识。
特记下,以备后日回顾。
0 0
- POJ 3984-迷宫问题 BFS
- poj 3984 迷宫问题(bfs)
- POJ 3984 迷宫问题 BFS
- poj 3984 迷宫问题 bfs
- POJ 3984 || 迷宫问题 (bfs
- POJ 3984 迷宫问题 BFS
- POJ 3984 迷宫问题(bfs)
- BFS-POJ-3984-迷宫问题
- 迷宫问题 POJ 3984 【BFS】
- POJ 3984 迷宫问题 (BFS)
- POJ 3984:迷宫问题【BFS】
- POJ 3984迷宫问题(BFS)
- poj 3984 迷宫问题 bfs
- POJ 3984:迷宫问题【BFS】
- POJ 3984 迷宫问题 BFS
- poj 3984 迷宫问题(bfs)
- POJ 3984 ,迷宫问题(bfs)
- poj 3984 迷宫问题 (BFS)
- 拷贝构造函数和赋值操作符
- POJ 2195-Going Home(KM算法/最小费用最大流算法)
- 07 ProgressDialog
- 2016.8.28测试解题报告(buylow,line,brush)
- NAS—IIS虚拟目录
- POJ 3984 迷宫问题 BFS
- leetcode Reconsrtuct Itinerary
- cf/codeforces#369-E - ZS and The Birthday Paradox- 数学+gcd+逆元+勒让德定理
- 数组作为函数参数传递
- HarvestAnimation
- SPOJ COT2 Count on a tree II 树上莫队
- 写给过去半年来的自己
- Map集合
- 基于RNN的个性化电影推荐尝试