poj-3984-迷宫问题
来源:互联网 发布:linux 查看目录树结构 编辑:程序博客网 时间:2024/06/11 00:58
原文链接 :poj-3984-迷宫问题
原题:
迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 25699 Accepted: 14956
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)
问题分析:对于迷宫问题,可以用dfs也可以用bfs,该题所求的是路径最短的解,所以采用bfs
AC代码:
//poj3984 迷宫问题 bfs #include<cstdio>#include<queue>using namespace std;const int maxn=5;const int dirsize=4;const int startx=1;const int starty=1;const int endx=maxn;const int endy=maxn;struct dirnode//方向的结构体 { int dirx,diry;}dir[dirsize]={{0,1},{1,0},{0,-1},{-1,0}}; struct node { int x,y;};int arr[maxn+2][maxn+2];node father[maxn+2][maxn+2];//存放父节点,用于输出 queue<node>q;void coutresult(){ node path[maxn*maxn]; int count=0; path[count].x=endx; path[count].y=endy; while(true) { if(path[count].x==startx&&path[count].y==starty) break; path[count+1]=father[path[count].x][path[count].y]; count++; } while(count>=0) { printf("(%d, %d)",path[count].x-1,path[count].y-1); if(count>0) printf("\n"); count--; }}void bfs(){ int i; node start;// start.x=startx;start.y=starty; q.push(start); while(!q.empty())//队列不为空就一直搜索 { node front; front=q.front();q.pop(); if(front.x==endx&&front.y==endy) { coutresult(); return; } for(i=0;i<dirsize;i++) { int nextx=front.x+dir[i].dirx; int nexty=front.y+dir[i].diry; if(arr[nextx][nexty]==0) { father[nextx][nexty]=front; node v; v.x=nextx; v.y=nexty; q.push(v); } } arr[front.x][front.y]=1; }}int main(){ int i,j; for(i=0;i<maxn+2;i++)//设置边界 { arr[i][0]=1; arr[maxn+1][i]=1; arr[0][i]=1; arr[i][maxn+1]=1; } for(i=1;i<=maxn;i++) for(j=1;j<=maxn;j++) scanf("%d",&arr[i][j]); bfs(); return 0;}
阅读全文
0 0
- poj 3984 迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- Poj 3984 迷宫问题
- 迷宫问题 poj 3984
- poj 3984迷宫问题
- poj 3984 迷宫问题
- POJ-3984-迷宫问题
- poj 3984- 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- poj 3984:迷宫问题
- POJ-3984-迷宫问题
- POJ 3984 迷宫问题
- poj 3984迷宫问题
- POJ 3984 迷宫问题
- POJ 3984 迷宫问题
- poj 3984 迷宫问题
- react-native 项目更名步骤
- next()和nextLine()的区别
- CSS样式的优先级
- C#连接MySql小例
- 求自定类型元素序列的中位数(25 分)
- poj-3984-迷宫问题
- SQL学习笔记(四)
- Docker安装官方MySQL镜像
- QMessageBox四种用法
- 获取主机信息
- 用HTML5的canvas标签画虚线
- 51nod1416-搜索&剪枝|并查集-两点
- Code Review for Java code
- 617. Merge Two Binary Trees