hdu Problem-1242 最基础的BFS
2015-08-03 22:37
232 查看
这道题的题意大概就是公主被困在监狱里,然后她的朋友去救她,‘.’表示道路,‘a’表示公主所在位置,‘r’表示朋友所在位置,求r到a的最短距离。
这题我的思路是用BFS,直接用stl的queue来做,具体在代码后都有注释。
这题我的思路是用BFS,直接用stl的queue来做,具体在代码后都有注释。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; #define maxn 210 char str[maxn][maxn]; int vis[maxn][maxn]; int dx[] = { 0,0,1,-1 };//x的方向 int dy[] = { 1,-1,0,0 };//y的方向 struct node { int x, y; int step; };//x,y记录点的坐标,step记录所走的距离; int main() { int n,m; int ax, by; while (~scanf("%d%d%*c", &n, &m)) {//%*c跳过一个字符(回车) queue<node>q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%c", &str[i][j]); if (str[i][j] == 'r') { ax = i; by = j; }//找到并记录公主的朋友的位置; } getchar(); } memset(vis, 0, sizeof(vis)); node e, s; int flag = 1; s.step = 0; s.x = ax; s.y = by; q.push(s); vis[s.x][s.y] = 1; while (!q.empty()) {//BFS实现广搜 s = q.front(); q.pop(); if (str[s.x][s.y] == 'a') { printf("%d\n", s.step); flag = 0; break; } for (int k = 0; k < 4; k++) { e.x = s.x + dx[k]; e.y = s.y + dy[k]; if (e.x< 0 || e.x >= n || e.y < 0 || e.y >= m || vis[e.x][e.y]||str[e.x][e.y] =='#') continue; if (str[e.x][e.y] == 'x') e.step = s.step + 2; else e.step = s.step + 1; q.push(e); vis[e.x][e.y] = 1; } } if(flag) printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; }
相关文章推荐
- 利用微软类库 Visual Studio International Pack 汉字转拼音首字母,完美解决多音字问题
- c#实现的守护进程
- Eclipse常用快捷键
- html5中的table相关内容
- Android Dalvik模式下劫持 Java 函数
- 2015080304 - 孤独的幸存者1随想
- Immunity Debugger PyCommands
- 20150803-UDP
- 今天发现一个android动画合集,明天开始研究
- Python进阶 函数式编程和面向对象编程等
- STL hash_map使用
- Python进阶 函数式编程和面向对象编程等
- 套接字&套接字地址结构和bind()函数
- Triangle LOVE
- 2、C语言和设计模式(继承、封装、多态)
- poj 1222 高斯消元详解
- 2015年8月3日工作日志-------赵鑫
- 软考-中级-软件设计师【完成】
- Java生成和操作Excel文件
- android.app.SuperNotCalledException错误