广度优先搜索之天使4

问题:

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M &lt;= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.<br><br>Angel's friends want to save Angel. Their task is: approach Angel. We assume that &quot;approach Angel&quot; is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.<br><br>You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)<br>

 代码:

 

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int n,m,ax,ay;//列,行,朋友的坐标
int go[4][2]={0,1,1,0,0,-1,-1,0};//走的方向
char map[201][201];int mark[201][201];//前一个是迷宫,后一个是标记走过的路
struct s//结构体绑定坐标,和时间
{
    int x,y,t;
};
void bfs()//广搜
{
    queue<s>q;//队列q结构体类型
    s a,b;//结构体a,b,a代表母亲,b是孩子
    a.x=ax;a.y=ay;a.t=0;//初始化a是朋友的坐标由此开始t为0
    mark[ax][ay]=1;//标记这点走过
    q.push(a);//进入队列
int flag=0;//标志
    while(!q.empty())//当队列不为空,即没到最后
    {
        a=q.front();//队列的形式是先进先出,标记此时的开头即为母亲
        q.pop();//进来就出去,母亲走了换孩子进来
      if(map[a.x][a.y]=='x')//如果碰上守卫先干掉
        {
            a.t++;//干掉守卫用时1
            map[a.x][a.y]='.';//这条路变成平路
            q.push(a);//再重新走这个位置
        }
        else
        {
            for(int i=0;i<4;i++)//四个孩子进来
            {
                b.t=a.t;b.x=a.x+go[i][0];b.y=a.y+go[i][1];//孩子由母亲衍出,坐标移动
                if(b.x>=0&&b.x<n&&b.y>=0&&b.y<=m&&mark[b.x][b.y]!=1&&map[b.x][b.y]!='#')//在围墙里未走过不是墙,可走
                {
                    b.t++;//走到这一位了,时间花1
                    if(map[b.x][b.y]=='r')//如果找到天使,输出时间,结束
                    {
                        cout<<b.t<<endl;
                    flag==1;//标志为1已成功
                        return ;
                    }


                    mark[b.x][b.y]=1;//没找到天使标记走过这路进行其孩子搜索
                    q.push(b);
                }
            }
        }
    }
    if(flag==0)//队列搜索结束还未成功输出以下的话
        cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
int main()
{
    while(cin>>n>>m)//输入nm
    {
        memset(mark,0,sizeof(mark));//初始化标记
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                char e;cin>>e;map[i][j]=e;//初始化迷宫里的字符
                if(e=='a') {ax=i;ay=j;}//记下朋友0的坐标
            }
        }
        bfs();//进入广搜
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值