HDU1026 Ignatius and the Princess I
2015-10-07 22:56
190 查看
解题思路:打印路径是关键,细节处理见代码。
View Code
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 105; char mapp[maxn][maxn]; int q[maxn*maxn*4][2]; //队列,刚开始没有乘以4,结果RE了 //dp[i][j]表示走到坐标(i,j)时所用的时间 //pre[x][y]存储当前点的前一个点在队列中的位置 int pre[maxn][maxn], dp[maxn][maxn], n, m, f, r, tmp, t; int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; void bfs() { f = 0, r = 1; //f为头指针,r为尾指针 q[0][0] = 0, q[0][1] = 0, dp[0][0] = 0; while(f != r) { int x = q[f][0], y = q[f][1]; tmp = f; //与32行对应 f ++; //出队列 for(int i = 0; i < 4; i++) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; int tt = dp[x][y] + 1; if(xx < 0 || xx >= n || yy < 0 || yy >= m || mapp[xx][yy] == 'X') continue; //如果当前点之前到达过,并且所用的时间小于或等于当前点,进行下一次循环。 if(dp[xx][yy] != -1 && dp[xx][yy] <= tt) continue; if(mapp[xx][yy] != '.') tt += mapp[xx][yy] - '0'; //遇到怪兽,原地扁他 pre[xx][yy] = tmp, q[r][0] = xx, q[r][1] = yy, dp[xx][yy] = tt, r ++; } } return ; } int Print(int x,int y) { int k = pre[x][y]; if(pre[x][y] == -1) return 0; //不能走,则返回; Print(q[k][0], q[k][1]); //好好体会这里的递归。 printf("%ds:(%d,%d)->(%d,%d)\n", t++, q[k][0], q[k][1], x, y); if(mapp[x][y] != '.') //说明是怪兽,原地痛打 for(int i = 0; i < mapp[x][y] - '0'; i++) //数字多大就打多久 printf("%ds:FIGHT AT (%d,%d)\n", t++, x, y); return 0; } int main() { while(~scanf("%d %d", &n, &m)) { for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) scanf(" %c", &mapp[i][j]); memset(dp, -1, sizeof(dp)); //都初始化为没有访问过 memset(pre, -1, sizeof(pre)); bfs(); //说明走不到这一点 if(dp[n-1][m-1] == -1) 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", dp[n-1][m-1]); t = 1; Print(n - 1,m - 1); //打印路径。 } printf("FINISH\n"); } return 0; }
View Code
相关文章推荐
- java,BufferedReader 输入
- 关于abstract 与接口的比较
- javascript,小数值舍入操作方法:ceil()、floor()、round()
- 基于HTML5的3D网络拓扑自动布局
- 从今天起,做一个幸福的人
- Apple Watch——Glance介绍与生命周期
- 第 二 十 三 天 :配 置 NFS 与 samba 服 务
- DOS命令解释程序的编写
- Android ListView和GridView异步加载图片
- MySQL备份和还原系列二:cp冷备份 和 mysqldump
- HTML5WebSocket实现点对点聊天
- javascript,函数声明和函数表达式
- ArrayList、Vector、HashMap、HashTable是如何扩容
- 实现图片的任意压缩,可以根据宽度或者高度进行
- 30 天学习 30 种新技术系列
- 堆内存分配
- 黑盒测试与其几个主要的方法
- Drawable加入动画机制(一)
- CentOS6下配置Django+Apache+mod_wsgi+Sqlite3过程
- 微软必应词典客户端的案例分析