NYOJ284坦克大战

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=284


BFS求最短路,这个题走到‘B’点是要花费2个时间,'E‘是1个时间,所以要用一个优先队列,优先级就是花费小的先出队,其余的就是模板了。


代码:


#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

#define inf 0x3f3f3f3f
int stx,sty;
int enx,eny;
int n,m;
int v[305][305];

typedef struct p
{
    int x,y;
    int step;
} Node;
struct cmp
{
    bool operator()(const Node a,const Node b)
    {
        return a.step > b.step;
    }
};
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
char s[305][305];
priority_queue<Node,vector<Node>,cmp> pq;
int flag;
int bfs()

{
    memset(v,0,sizeof v);
    Node start;
    start.x = stx;
    start.y = sty;
    start.step = 0;
    pq.push(start);
    while(!pq.empty())
    {
        Node head = pq.top();
        pq.pop();
        for(int i = 0; i < 4; ++i)
        {
            Node t;
            t.x = head.x + dx[i];
            t.y = head.y + dy[i];
            if(t.x == enx && t.y == eny)
            {
                return head.step + 1;
            }
            if(t.x < 0 || t.x > n - 1 || t.y < 0 || t.y > m - 1 ||s[t.x][t.y] == 'R'|| s[t.x][t.y] == 'S')
                continue;
            if(!v[t.x][t.y])
            {
                if(s[t.x][t.y] == 'B')
                    t.step = head.step + 2;
                else if(s[t.x][t.y] == 'E')
                    t.step = head.step + 1;
                pq.push(t);
                v[t.x][t.y] = 1;
            }
        }
    }
    return -1;
}
void clear()

{
    while(!pq.empty())
        pq.pop();
}
int main()

{
    while(~scanf("%d%d",&n,&m),m + n)
    {
        for(int i = 0; i < n; ++i)
        {
            scanf("%s",s[i]);
            for(int j = 0; j < m; ++j)
                if(s[i][j] == 'Y')
                {
                    stx = i;
                    sty = j;
                }
                else if(s[i][j] == 'T')
                {
                    enx = i;
                    eny = j;
                }
        }
        //printf("%d %d %d %d\n",stx,sty,enx,eny);
        printf("%d\n",bfs());
        clear(); // 一定要有这个,否则WA
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值