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;
}

 

posted @ 2017-07-20 13:47  Wisdom+.+  阅读(301)  评论(0编辑  收藏  举报