POJ 2312 Battle City BFS+优先队列

POJ 2312 Battle City

博客搬新家,以后就是基本只在自己的独立博客进行更新,欢迎访问。http://zihengoi.cn

题目描述:

  题目链接:POJ 2312 Battle City

题目大意:

  坦克大战游戏中需要让坦克 Y 在给定的地图中到达指定的位置 T 。其中移动至空地 E 算一次操作,砖墙 (B 因为需要先打破再通过故算两次操作,金属墙和河不能通过。每次可向上下左右任意方向操作一次。求到达目标的最少操作数。若不能到达则输出 1

解题思路:

  因为题目要求最少操作数,即求从初始地点到目标地点的最短路,即使用 BFS 。又因为, B E对应的权值不一样,所以用优先队列,使操作数少的状态优先出队。

复杂度分析(这个最近在学怎么算,如果算错希望指出):

时间复杂度 : O(n2)
空间复杂度 : 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
************************************/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值