迷宫问题(输出路径)
2016-01-24 20:31
267 查看
迷宫问题
Time Limit:1000MS Memory
Limit:65536KB 64bit IO
Format:%I64d & %I64u
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
Sample Output
思路:题意很简单,关键是用怎样的方式将路径保存下来,第一次接触这种需要输出路径的题,参考了别人的方法。在结构体中用一个变量来保存当前状态的上一个状态,采用模拟队列来实现出队和入队,用递归的方式来输出途径。
代码如下:
Time Limit:1000MS Memory
Limit:65536KB 64bit IO
Format:%I64d & %I64u
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)
思路:题意很简单,关键是用怎样的方式将路径保存下来,第一次接触这种需要输出路径的题,参考了别人的方法。在结构体中用一个变量来保存当前状态的上一个状态,采用模拟队列来实现出队和入队,用递归的方式来输出途径。
代码如下:
#include"cstdio" #include"cstring" #include"iostream" #include"algorithm" using namespace std; int top,rear; int maze[10][10]; int movex[4] = {1,-1,0,0}; //x前进方式 int movey[4] = {0,0,1,-1}; //y前进方式 struct node { int x,y,pre; //pre用来保存当前状态的前一个状态 }node[100]; bool is_block(int x,int y) //判断当前位置能不能走 { if(x<0 || x>4 || y<0 || y>4) { return true; } if(maze[x][y]) { return true; } return false; } void output(int i) //递归输出走过的坐标 { if(node[i].pre != -1) { output(node[i].pre); printf("(%d, %d)\n",node[i].x,node[i].y); } } void bfs(int x,int y) { node[top].x = x; node[top].y = y; node[top].pre = -1; while(top < rear) //队列不为空 { for(int i = 0;i < 4;i++) { int xx = movex[i]+node[top].x; int yy = movey[i]+node[top].y; if(xx == 4 && yy == 4) //走到迷宫的右下角,输出路径 { output(top); } if(is_block(xx,yy)) { continue; } else { maze[xx][yy] = 1; //走过的地方变为1(墙壁),相当于标记为已走过 node[rear].x = xx; node[rear].y = yy; node[rear].pre = top; rear++; //入队 } } top ++; //出队 } } int main() { while(~scanf("%d",&maze[0][0])) { for(int i = 1;i < 5;i++) { scanf("%d",&maze[0][i]); } for(int i = 1;i < 5;i++) { for(int j = 0;j < 5;j++) { scanf("%d",&maze[i][j]); } } top = 0,rear = 1; puts("(0, 0)"); bfs(0,0); puts("(4, 4)"); } return 0; }
相关文章推荐
- ecshop 函数列表大全
- 实战:使用Docker配置ubuntu下的scrapy爬虫环境
- 堆排序算法
- [转]超全面的.NET GDI+图形图像编程教程
- 机器学习中的数学(2)-线性回归,偏差、方差权衡
- Block上篇
- Android HTTPS认证之Volley封装
- 166 Fraction to Recurring Decimal
- Hello world程序的生命周期
- BZOJ2818 Gcd
- [Struts 2系列] Struts 2入门之HelloWorld
- ExpandableListView
- 在Linux上编译TCMalloc
- Android 开发环境搭建
- 数据结构与算法知识大纲
- UITableView练习一
- 51nod 1640 天气晴朗的魔法 prime队列+最小生成树+最大生成树+邻接表
- 【NOI2001】炮兵阵地
- Android开发之按键、触摸屏和手势输入专业压力測试方法
- HTML笔记五,HTML5的多媒体支持