Codeforces 197D - Infinite Maze

197D - Infinite Maze

思路:bfs,如果一个点被搜到第二次,那么就是符合要求的。

用vis[i][j].x,vis[i][j].y表示i,j(i,j是取模过后的值)这个点第一次被搜到的位置,用vis[(next.x%n+n)%n][(next.y%m+m)%m]标记,因为位置可以为负数(绝对值很大的负数)。

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=1555;
const int INF=0x3f3f3f3f;
char Map[N][N];
int n,m;
int sx,sy;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
struct node
{
    int x,y;
}vis[N][N];
bool bfs(int x,int y)
{
    node now,next;
    now.x=x;
    now.y=y;
    queue<node>q;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            if(Map[(next.x%n+n)%n][(next.y%m+m)%m]!='#')
            {
                if(vis[(next.x%n+n)%n][(next.y%m+m)%m].x==INF)
                {
                    vis[(next.x%n+n)%n][(next.y%m+m)%m].x=next.x;
                    vis[(next.x%n+n)%n][(next.y%m+m)%m].y=next.y;
                    //cout<<next.x<<' '<<next.y<<endl;
                    q.push(next); 
                }
                else if(next.x!=vis[(next.x%n+n)%n][(next.y%m+m)%m].x||next.y!=vis[(next.x%n+n)%n][(next.y%m+m)%m].y)
                {
                    return true;
                }
            }
        }
    }
    return false;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    memset(vis,INF,sizeof(vis));
    cin>>n>>m;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            cin>>Map[i][j];
            if(Map[i][j]=='S')
            sx=i,sy=j;
        }
    }
    if(bfs(sx,sy))cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/widsom/p/7210807.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值