您的位置:首页 > 其它

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
************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: