YbtOJ练习:广搜 3 追捕小狗

http://noip.ybtoj.com.cn/contest/19/problem/3

这道题仍然可以用例题逃离噩梦的思路来解决。

#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int> PII;
const int N=105;
char g[N][N];
int n;
int dis[N][N];
bool vis[N][N];
PII q[N*N];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int st;
int ans;
int sx,sy,tx,ty;
bool bfs()
{
    int times=0;
    int hh=0,tt=0;
    q[0]=make_pair(sx,sy);
    vis[sx][sy]=1;dis[sx][sy]=0;
    while(hh<=tt)
    {
        //times++;
        int S=tt-hh+1;
        for(int j=1;j<=S;j++)
        {
            PII tmp=q[hh++];
            for(int i=0;i<4;i++)
            {
                int nx=tmp.x+dx[i],ny=tmp.y+dy[i];
                if(nx<0||nx>=n||ny<0||ny>=n) continue;
                if(vis[nx][ny]) continue;
                if(g[nx][ny]=='*') continue;
                dis[nx][ny]=dis[tmp.x][tmp.y]+1;
                //cout<<"人"<<' '<<nx<<' '<<ny<<' '<<dis[nx][ny]<<endl;
                //if(nx==tx&&ny==ty) 
            //    {
            //        ans=dis[nx][ny];
            //        return true;
            //    }
                vis[nx][ny]=1;
                q[++tt]=make_pair(nx,ny);
            }
        }
        if(vis[tx][ty]) 
        {
            printf("%d\n",times);
            return true;
        } 
        //times++;
        //cout<<"狗"<<' '<<tx<<' '<<ty<<endl;
        int nx=tx+dx[st],ny=ty+dy[st];
        int cnt=0;
        while((g[nx][ny]=='*'||nx<0||nx>=n||ny<0||ny>=n)&&cnt<=3)
        {
            st=(st+1)%4;
            nx=tx+dx[st];ny=ty+dy[st];
            cnt++;
            if(cnt>3) return false;
        }
        tx=nx;ty=ny;
        //if(vis[tx][ty]) 
    //    {
        //    printf("%d\n",times);
    //        return true;
        //} 
        times++;
    }
    return false;
}
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%s",g[i]);
    for(int i=0;i<n;i++)
     for(int j=0;j<n;j++)
     {
         if(g[i][j]=='F') sx=i,sy=j;
         else if(g[i][j]=='J') tx=i,ty=j;
     }
    //cout<<sx<<' '<<sy<<' '<<tx<<' '<<ty<<endl;
    
    if(!bfs()) puts("No solution.");
    return 0;
}

在判定是否相遇时需要注意此时times的值是多少。

posted @ 2020-08-17 00:12  Gold_stein  阅读(333)  评论(0编辑  收藏  举报