HDU 1026 Ignatius and the Princess I
2015-08-15 18:05
302 查看
HDU 1026 Ignatius and the Princess I
http://acm.hdu.edu.cn/showproblem.php?pid=1026
依然是BFS的题目,这次不同的是需要把路径进行记录。计算最短路径的值跟裸题一样,就不重复了,主要的不同是用pre数组把每个点的前一个元素记录下来,最后用迭代的方式把路径输出。
http://acm.hdu.edu.cn/showproblem.php?pid=1026
依然是BFS的题目,这次不同的是需要把路径进行记录。计算最短路径的值跟裸题一样,就不重复了,主要的不同是用pre数组把每个点的前一个元素记录下来,最后用迭代的方式把路径输出。
#include<cstdio> #include<queue> #include<cstring> #define INF 10000000 using namespace std; char maze[120][120]; int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; int dis[120][120]; typedef pair<int, int> P; int n, m; P pre[120][120]; void bfs(){ queue<P> que; que.push(P(0, 0)); dis[0][0] = 0; while(!que.empty()){ P p = que.front(); que.pop(); //if(p.first == n - 1 && p.second == m - 1) break; for(int i = 0;i < 4;i++){ int nx = p.first + dx[i], ny = p.second + dy[i]; if(nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != 'X'){ if(maze[nx][ny] == '.'){ if(dis[p.first][p.second] + 1 < dis[nx][ny]){ dis[nx][ny] = dis[p.first][p.second] + 1; pre[nx][ny].first = p.first; pre[nx][ny].second = p.second; que.push(P(nx, ny)); } } else{ if(dis[p.first][p.second] + (maze[nx][ny] - '0') + 1 < dis[nx][ny]){ dis[nx][ny] = dis[p.first][p.second] + (maze[nx][ny] - '0') + 1; pre[nx][ny].first = p.first; pre[nx][ny].second = p.second; que.push(P(nx, ny)); } } } } } } void print_pre(int i, int j){ if(pre[i][j].first == -1) return ; print_pre(pre[i][j].first, pre[i][j].second); if(maze[i][j] == '.') printf("%ds:(%d,%d)->(%d,%d)\n",dis[i][j],pre[i][j].first, pre[i][j].second,i, j); else{ int num = maze[i][j] - '0'; int t = dis[i][j] - num; printf("%ds:(%d,%d)->(%d,%d)\n",t++, pre[i][j].first, pre[i][j].second, i, j); for(int k = 1;k <= num;k++){ printf("%ds:FIGHT AT (%d,%d)\n",t++, i, j); } } } main(){ while(~scanf("%d %d", &n, &m)){ getchar(); for(int i = 0;i < n;i++){ gets(maze[i]); } for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ dis[i][j] = INF; } } pre[0][0].first = pre[0][0].second = -1; bfs(); if(dis[n-1][m-1] == INF) printf("God please help our poor hero.\n"); else{ printf("It takes %d seconds to reach the target position, let me show you the way.\n",dis[n-1][m-1]); print_pre(n-1,m-1); } puts("FINISH"); } }
相关文章推荐
- 【总结】《机房收费系统》——信息不能输入数据库
- 函数的重写,重载
- Android layout适配4种方式笔记小结
- UIButton如何正确调整imageView及titleLabel的位置
- Island Transport
- hdu 5313 Bipartite Graph(dfs染色 或者 并查集)
- (传输层)UDP协议
- 篮球场上的心理作用
- RTB业务知识2-Open-RTB全景
- Java的JNI:使用Java调用C程序(入门)
- Openerp管理权限的方法
- Android大图片裁剪终极解决方案
- (传输层)TCP协议
- 线性空间和线性变换
- Scala学习笔记(四):从文件里读取文本行
- **HDU 4412 - Sky Soldiers(区间DP)
- struts2 多文件上传与下载
- HDU1281 棋盘游戏(坐标平面 ,行列匹配+求关键点)
- centos yum搭建nginx php mysql 环境
- Passive Vulnerability Scanner