POJ 3083 Children of the Candy Corn
2015-10-14 01:21
323 查看
DFS和BFS的综合应用。分别输出一个迷宫由起点开始,左手优先路径长度,右手优先路径长度,以及最短路径长度。其中,前两个采用dfs,而最后一个采用bfs。注意下标w, h不要搞混,好容易wa...另外,用(i + 3) % 4 和 (i + 1) % 4表示方向,也是参考了别人的代码才理解的,画个图,试几个例子就很好理解了。
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <cstring> using namespace std; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, -1, 0, 1}; char maze[45][45]; bool flag[45][45]; int w, h; int cnt; bool p; struct node { int x, y, step; }; void dfsl(int x, int y, int i) { if (p || maze[x][y] == 'E') { p = true; return; } int cx = x + dx[i]; int cy = y + dy[i]; while (cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#') { i = (i + 3) % 4; cx = x + dx[i]; cy = y + dy[i]; } cnt++; dfsl(cx, cy, (i + 1) % 4); } void dfsr(int x, int y, int i) { if (p || maze[x][y] == 'E') { p = true; return; } int cx = x + dx[i]; int cy = y + dy[i]; while (cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#') { i = (i + 1) % 4; cx = x + dx[i]; cy = y + dy[i]; } cnt++; dfsr(cx, cy, (i + 3) % 4); } int bfs(int start_x, int start_y) { queue<node> q; node start; start.x = start_x; start.y = start_y; start.step = 1; q.push(start); flag[start_x][start_y] = 1; while (!q.empty()) { node n = q.front(); q.pop(); for (int i = 0; i < 4; i++) { int cx = n.x + dx[i]; int cy = n.y + dy[i]; if (flag[cx][cy] || cx < 0 || cx >= h || cy < 0 || cy >= w || maze[cx][cy] == '#') continue; start.x = cx; start.y = cy; start.step = n.step + 1; flag[cx][cy] = 1; if (maze[cx][cy] == 'E') return start.step; q.push(start); } } } int main() { int t; int start_x, start_y; scanf("%d", &t); while (t--) { memset(flag, 0, sizeof(flag)); scanf("%d%d", &w, &h); for (int i = 0; i < h; i++) { scanf("%s", &maze[i]); for (int j = 0; j < w; j++) { if (maze[i][j] == 'S') { start_x = i; start_y = j; } } } cnt = 1, p = false; dfsl(start_x, start_y, 0); printf("%d ", cnt); cnt = 1, p = false; dfsr(start_x, start_y, 0); printf("%d ", cnt); printf("%d\n", bfs(start_x, start_y)); } }
相关文章推荐
- Nginx负载均衡器让后端RS记录真实IP
- 分布式系统的难点
- 关于windowsAPI录音
- 推拉模型
- IOC容器中Bean的生命周期方法
- android-UI组件实例大全(一)------TextView文本框
- Effective Java
- ngnix 配置错误页面
- windows录音程序原理
- 数据库分析与设计总结
- 分布式事务
- android view类的xml属性
- 使用键盘来改变形状中的线条样式,或移动鼠标来创建一个新的形状
- android UI属性:inputType
- 领域驱动设计
- JVM学习笔记(四)------内存调优
- iOS多态特性
- JVM学习笔记(三)------内存管理和垃圾回收
- android系统的常用权限
- 运算符重载