2014计算机学科夏令营上机考试F:Battle City(改进的BFS——优先队列)

在这里插入图片描述
在这里插入图片描述

题目大意

'Y’为起点,'T’为终点,'S’和’R’不可搜索,'E’为消耗为1的路径,'B’为消耗为2的路径。
要求从起点到终点的消耗最小。

思路分析

本题看来就是一道典型的BFS问题,遍历到终点的层次就是路径的消耗。但由于路径上存在不同消耗的路径,此时队列中的每个元素并不是都等价,由于希望最后到达终点的层次最小,所以每次从队列中希望取出层次最小的结点。
所以不能用模板中的队列queue来存储结点,要想到用小顶堆优先队列priority_queue来解决。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

struct node
{
    int x, y;
    int layer;
}Start, End, Temp;

struct cmp
{
    bool operator() (node a, node b)
    {
        return a.x > b.x; // 小顶堆
    }
};

const int maxn = 310;
char map[maxn][maxn];
bool inq[maxn][maxn] = {false};
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
priority_queue<node, vector<node>, cmp > q; // 小顶堆

int row, col;

void init()
{
    fill(inq[0], inq[0]+maxn*maxn, false);
    while(!q.empty()) // 优先队列不支持clear清空
    {
        q.pop();
    }
}

int judge(int x, int y)
{
    if(x<0 || x>=row || y<0 || y>=col)
    {
        return 0;
    }
    if(inq[x][y]==true || map[x][y]=='R' || map[x][y]=='S')
    {
        return 0;
    }
    if(map[x][y] == 'B')
    {
        return 2;
    }
    return 1;
}

int BFS()
{
    q.push(Start);
    inq[Start.x][Start.y] = true;
    while(!q.empty())
    {
        node front = q.top();
        q.pop();
        if(front.x==End.x && front.y==End.y) 
        {
            return front.layer; 
        }        
        for(int i=0; i<4; i++)
        {
            int xx = front.x + dx[i];
            int yy = front.y + dy[i];
            if(judge(xx, yy) != 0)
            {
                Temp.x = xx;
                Temp.y = yy;
                Temp.layer = front.layer + judge(xx, yy);
                q.push(Temp);
                inq[xx][yy] = true;
            }
        }
    }
    return -1;
}

int main()
{
    // freopen("input.txt", "r", stdin);
    while(cin >> row >> col)
    {
        if(row==0 && col==0)
        {
            break;
        }
        init();
        for(int x=0; x<row; x++)
        {
            for(int y=0; y<col; y++)
            {
                cin >> map[x][y];
                if(map[x][y] == 'Y')
                {
                    Start.x = x;
                    Start.y = y;
                    Start.layer = 0;
                }
                if(map[x][y] == 'T')
                {
                    End.x = x;
                    End.y = y;
                }
            }
        }
        cout << BFS();
    } 
    // fclose(stdin);

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值