POJ 2312 Battle City

bfs+优先队列

十分裸的一道题目

其实单纯的BFS也能做,就是在遇到‘R’的时候停一步步扩张,然后下次扩展的时候step+2就行了

主要就是学习一个优先队列的事情

有了优先队列这题就比较简单了,基本就和普通的bfs一样了

需要重载 < 来排序

另外hdu 1242 rescue也是一道差不多的题目,有兴趣的话可以去试一下的

代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
struct node
{
	int x,y,step;  //定义一个优先队列
	friend bool operator<(node a, node b)
	{
		return a.step> b.step;       //从小到大排序
	}
}you,now,next;
bool vis[301][301];
char way[301][301];
int m,n,sx,sy,ex,ey;
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
bool check(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m)
        return true;
    return false;
}
int bfs()
{
    priority_queue<node> q;
    you.x=sx;
    you.y=sy;
    you.step=0;
    q.push(you);
    while(!q.empty())
    {
        now=q.top();
        q.pop();
        for(int i=0;i<4;i++)
        {
            int fx,fy;
            fx=now.x+dir[i][0];
            fy=now.y+dir[i][1];
            if(check(fx,fy)&&!vis[fx][fy]&&way[fx][fy]!='R'&&way[fx][fy]!='S')
            {
                if(way[fx][fy]=='B')
                {
                    next.x=fx;
                    next.y=fy;
                    next.step=now.step+2;
                }
                else if(way[fx][fy]=='E')
                {
                    next.x=fx;
                    next.y=fy;
                    next.step=now.step+1;
                }
                if(fx==ex&&fy==ey)
                {
                    next.step=now.step+1;
                    return next.step;
                }
                vis[fx][fy]=true;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    freopen("in.txt","r",stdin);
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        if(n==0&&m==0)
            break;
        memset(vis,0,sizeof vis);
        memset(way,0,sizeof way);
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                cin>>way[i][j];
                if(way[i][j]=='Y')
                {
                    sx=i;
                    sy=j;
                    vis[i][j]=true;
                }
                if(way[i][j]=='T')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        int time = bfs();
        printf("%d\n",time);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值