10.3 弱校 B Help the Princess! 搜索

题目描述:

https://acm.bnu.edu.cn/v3/contest_show.php?cid=8504#problem/B

题目分析:

由于题目是pdf格式给出的 我就扔连接算了~~
题目大意就是一个n*m的地图,其中有一个’@’表示公主,有若干个’$’表示士兵,一个’%’表示出口,’#’表示墙(无法进入),’.’表示可以走的地方。其中公主想要逃亡到出口,有士兵追击,若公主能够走到出口且没有遇到士兵,就输出’Yes’,否则输出’No’。特别注意如果公主逃到出口时士兵也到了出口,公主也不能成功逃亡。

其实就是倒过来搜就可以,将’%’也就是出口当做搜索起点,记录搜索到公主和士兵的最短时间,如果公主时间短,则’Yes’,否则’No’。

转变思维很重要!!

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <queue>

using namespace std;
const int INF=0x3f3f3f3f;
int n,m;
char map[220][220];
bool vis[220][220];
int sx,sy;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct Node
{
    int x,y,s;
    Node(int _x=0, int _y=0, int _s=0)
    {
        x=_x;
        y=_y;
        s=_s;
    }
};

bool bfs()
{
    int ps=INF,ss=INF;
    queue<Node>q;
    int s=0;
    memset(vis,false,sizeof(vis));
    q.push(Node(sx,sy,s));
    vis[sx][sy]=true;
    while(!q.empty())
    {
        Node t=q.front();
        q.pop();
        for(int i=0; i<4; i++)
        {
            int nx=t.x+dir[i][0];
            int ny=t.y+dir[i][1];
            int ns=t.s+1;
            if (vis[nx][ny]) continue;
            vis[nx][ny]=true;
            if (nx<=0 || nx>n || ny<=0 || ny>m) continue;
            if (map[nx][ny]=='#') continue;
            if (map[nx][ny]=='@')
            {
                ps=min(ns,ps);
                continue;
            }
            if (map[nx][ny]=='$')
            {
                ss=min(ns,ss);
                continue;
            }
            q.push(Node(nx,ny,ns));
        }
    }
    if (ps<ss) return true;
    else return false;
}

int main()
{
    while(scanf("%d%d",&n,&m)!=-1)
    {
        memset(map,0,sizeof(map));
        for(int i=1; i<=n; i++)
        {
            scanf("%s",map[i]+1);
            for(int j=1; j<=m; j++)
            {
                if (map[i][j]=='%')
                {
                    sx=i;
                    sy=j;
                }
            }
        }
        if (bfs()) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值