POJ 2312 Battle City BFS+优先队列
2015-08-21 10:29
204 查看
POJ 2312 Battle City
题目描述:
题目链接:POJ 2312 Battle City题目大意:
坦克大战游戏中需要让坦克(Y)(Y)在给定的地图中到达指定的位置(T)(T)。其中移动至空地(E)(E)算一次操作,砖墙(B)(B)因为需要先打破再通过故算两次操作,金属墙和河不能通过。每次可向上下左右任意方向操作一次。求到达目标的最少操作数。若不能到达则输出−1-1。解题思路:
因为题目要求最少操作数,即求从初始地点到目标地点的最短路,即使用BFSBFS。又因为,BB和EE对应的权值不一样,所以用优先队列,使操作数少的状态优先出队。复杂度分析(这个最近在学怎么算,如果算错希望指出):
时间复杂度 :O(n2)O(n^2)空间复杂度 :O(n)O(n)
AC代码
#include <cstdio> #include <cstring> #include <string> #include <iostream> #include <algorithm> #include <queue> using namespace std; struct node{ int x,y; int ans; bool operator < (const node &a) const{ return ans > a.ans; } }; const int maxn = 310; int m,n; int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int gm[maxn][maxn]; int bfs(int x0, int y0){ priority_queue <node>Q; node tmp; tmp.x = x0; tmp.y = y0; tmp.ans = 0; Q.push(tmp); while(!Q.empty()){ tmp = Q.top(); Q.pop(); for(int i = 0; i < 4; i++){ int xt = tmp.x + dir[i][0]; int yt = tmp.y + dir[i][1]; if(xt <= m && xt > 0 && yt <= n && yt > 0){ if(gm[xt][yt] == 3){ return tmp.ans + 1; } if(gm[xt][yt]){ node tmp2; tmp2.x = xt; tmp2.y = yt; tmp2.ans = tmp.ans + gm[xt][yt]; Q.push(tmp2); gm[xt][yt] = 0; } } } } return -1; } int main(){ int x0, y0; while(scanf("%d%d",&m,&n),m||n){ memset(gm,0,sizeof(gm)); for(int i = 1; i <= m; i++){ getchar(); for(int j = 1; j <= n ;j++){ char t = getchar(); switch(t){ case 'Y': x0 = i, y0 = j; break; case 'B': gm[i][j] = 2; break; case 'E': gm[i][j] = 1; break; case 'T': gm[i][j] = 3; break; } } } printf("%d\n",bfs(x0,y0)); } return 0; } /***************************************** 3 4 YBEB EERE SSTE 5 4 YEEB SSRE SEEE EERE SSTE 0 0 ************************************/
相关文章推荐
- VS错误 FileTracker : error FTK1011:
- 解决使用findnext相关函数在64位编译环境下遍历文件夹下的文件
- tar 命令
- [转] 自定义取色函数
- [LeetCode] Find Minimum in Rotated Sorted Array
- android:修改PagerTabStrip中的背景颜色,标题字体的样式、颜色和图标以及指示条的颜色
- MVC中用View.bag保存json字符串。在js中使用,不用ajax请求。。。。
- 8月18日全球域名商(国际域名)解析新增量TOP25
- hdu 2066 一个人的旅行-spfa
- mongodb创建集合
- hdu 1016 Prime Ring Problem(DFS)
- codeforces 177B2 B2. Rectangular Game(数论)
- href="javascript:void(0);"与#差异
- css style与class之间的区别,cssclass
- AD域撤销域用户管理员权限方案
- HTTP协议请求方式: 中GET、POST和HEAD的介绍
- bzoj1251: 序列终结者
- iOS开发~CocoaPods使用详细说明
- UVa 1513 / UVALive 5902 Movie collection (树状数组)
- java中abstract怎么使用