ZOJ 1649 Rescue
来源:互联网 发布:泄密数据库下载 编辑:程序博客网 时间:2024/06/04 19:27
本题要求从r 位置出发到达Angel所在位置并且所需时间最少,适合采用BFS求解。但是BFS算法求出来的最优解通常是步数最少的解,而在本题中,步数最少的解不一定是最优解.
在本题中,并没有使用标明各位置是否访问过的状态数组visited,也没有在BFS过程中将访问过的相邻位置设置成不可再访问,那么BFS过程会不会无限搜索下去呢?实际上是不会的,因为从某个位置出发判断是否需要将它的相邻位置(x,y)入队列时,条件是这种走法比之前走到(x,y)位置所花时间更少;如果所花时间更少,则(x,y)位置会重复入队列,但不会无穷下去,因为到达(x,y)位置的最少时间肯定是有下界的。
点击打开 题目
#include <iostream>#include <cstring>#include <queue>using namespace std;const int MAXN = 210;const int INF = 1000000;//走到每个位置初始值设置为无穷大char Graph[MAXN][MAXN];//储存图struct Node//表示到达某个方格时的状态{ int x, y;//方格的坐标 int time;//走到当前位置所需要的时间};queue <Node> Q;//队列中的结点为Angel朋友所处的位置int mintime[MAXN][MAXN];//mintime[i][j]表示到达Graph[i][j]所需要的最少时间int N, M;int dir[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} };int ax, ay;//Angel所处的位置bool Cango(int x, int y)//判断当前位置是否满足可走的条件{ if(x >= 0 && y >= 0 && x < N && y < M && Graph[x][y] != '#') return true; else return false;}int BFS( Node s ){ int i; Node hd;//从队列头出队列的位置 Q.push( s ); while( !Q.empty() ) { hd = Q.front(); Q.pop(); for(i = 0; i < 4; ++i) { //判断是否能走到相邻的x,y位置 int x = hd.x + dir[i][0] , y = hd.y + dir[i][1]; if(Cango(x, y)) { Node t; t.x = x, t.y = y; t.time = hd.time + 1; if(Graph[x][y] == 'x')//杀死警察时间加一 t.time++; if(t.time < mintime[x][y])//如果到达当前位置是最少的,则t需要进队列 { Q.push( t ); mintime[x][y] = t.time; } } } } return mintime[ax][ay];}int main(){ int i, j; int rx, ry; while(cin>>N>>M) { memset(Graph, 0, sizeof(Graph)); for(i = 0; i < N; ++i) cin>>Graph[i]; for(i = 0; i < N; ++i) { for(j = 0; j < M; ++j) { mintime[i][j] = INF; if(Graph[i][j] == 'a') ax = i, ay = j; if(Graph[i][j] == 'r') rx = i, ry = j; } } mintime[rx][ry] = 0; Node start; start.x = rx, start.y = ry; start.time = 0; int mint = BFS( start ); if(mint < INF) cout<<mint<<endl; else cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; } return 0;}
- zoj 1649 Rescue
- ZOJ 1649 Rescue
- zoj 1649 Rescue
- ZOJ 1649 Rescue (BFS)
- zoj 1649 rescue (bfs)
- ZOJ-1649-Rescue
- zoj 1649 Rescue
- ZOJ:1649 Rescue
- ZOJ 1649 Rescue
- ACM ZOJ 1649 (Rescue)
- ZOJ(1649)Rescue
- ZOJ 1649 Rescue
- zoj 1649 Rescue
- zoj 1649 Rescue
- ZOJ 1649 : Rescue - BFS
- ZOJ 1649 Rescue
- zoj 1649 Rescue
- zoj 1649 Rescue bfs
- 关于重载、重写、重定义
- Spring如何装配Map
- meta标签中的http-equiv属性使用介绍
- HTML5 JavaScript实现图片文字识别与提取
- CODE 64: Text Justification
- ZOJ 1649 Rescue
- 收藏一下,很全面的总结// 程序员到项目经理:从内而外的提升(比较全面的介绍)
- 归并排序(MergeSort)Java实现
- SQL语句
- Linux——查看磁盘信息
- OEA 中的业务控制器设计模式
- asp.net 中超链接的动态设置
- 为何使用NSLocalizedString
- How Virtual Memory Works