hdu 1242 Rescue(BFS搜索)
2015-07-19 14:31
281 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
题 意:天使的朋友从r位置出发去a位置救天使。
思 路:从a位置开始进行BFS遍历,找到到r位置时所花费的时间(也可用优先队列进行处理)。
代码如下:
题 意:天使的朋友从r位置出发去a位置救天使。
思 路:从a位置开始进行BFS遍历,找到到r位置时所花费的时间(也可用优先队列进行处理)。
代码如下:
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <queue> #include <algorithm> using namespace std; char vis[220][220]; int n, m, ans, x1, y1; struct node { int x,y,t; }; int dx[4]= {1,-1,0,0},dy[4]= {0,0,1,-1}; int bfs() { queue<node>q; while( !q.empty() ) q.pop(); node kai,dai; vis[x1][y1]='#'; kai.x=x1; kai.y=y1; kai.t=0; q.push(kai); while( !q.empty() ) { kai = q.front(); q.pop(); if( vis[kai.x][kai.y] == 'r' ) return kai.t; for( int i = 0 ; i < 4; i ++ ) { int xx=kai.x+dx[i]; int yy=kai.y+dy[i]; if( yy > 0 && yy <= m && xx > 0 && xx <=n && vis[xx][yy] != '#' ) { if( vis[xx][yy] == 'r' ) return kai.t+1; dai.x=xx; dai.y=yy; dai.t=kai.t+1; if( vis[xx][yy] == 'x' ) dai.t++; q.push(dai); vis[xx][yy]='#'; } } } return -1; } int main() { while( scanf ( "%d %d", &n, &m ) != EOF ) { for ( int i = 1; i <= n; i ++ ) for( int j = 1; j <= m; j ++ ) { scanf ( " %c", &vis[i][j] ); if( vis[i][j] == 'a' ) { x1=i; y1=j; } } ans=bfs(); if(ans>-1) printf("%d\n",ans); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }
相关文章推荐
- Javascript SHA-1:Secure Hash Algorithm
- [转]可视化的数据结构和算法
- 统计文件中不小于某一长度的单词的个数(泛型算法实现)
- 使用他人的MD5编码类,修改形成密码串
- Extracting Structured Data from Web Pages
- (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.13使用CCTexture2DMutable调换调色盘
- Java中3DES加密
- Refactoring Notes-Refactoring Methods(3)
- 图书馆管理程序~~不过貌似功能!!有空再修修
- trainging contest#2(2011成都现场赛)I BY Hyoga
- C/C++头文件包含内容概览
- 堆栈的应用(1) 平衡符号 C++实现
- 程序员编程艺术第一章、左旋转字符串
- 程序员编程艺术:第三章续、Top K算法问题的实现
- 程序员编程艺术:第四章、现场编写类似strstr/strcpy/strpbrk的函数
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- 程序员编程艺术:第七章、求连续子数组的最大和
- 程序员编程艺术:第八章、从头至尾漫谈虚函数
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第十章、如何给10^7个数据量的磁盘文件排序