http://codeforces.com/contest/196/problem/B
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze
and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if
and only if cell is
a wall.
In this problem is
a remainder of dividing number a by number b.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1500) — the height and the width of the maze that the boy used to cyclically tile the plane.
Each of the next n lines contains m characters — the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point.
The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.
Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).
5 4 ##.# ##S# #..# #.## #..#
Yes
5 4 ##.# ##S# #..# ..#. #.##
No
In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.
In the second sample the vertical path is blocked. The path to the left doesn't work, too — the next "copy" of the maze traps the boy.
題意:這個迷宮是可以上下左右無限拼接的,問從S點出發是不是能走到無限遠。
一開始,自己寫的bfs,wa4和mle6,很尷尬,看了別人寫的題解才摸索出來
思路:要從S能走到無限遠,其實就是S本身能到某個點,然後這條路在x>=n||x<0||y>=m||y<0取模以後又可以到達這個點,即第二次到達,就算聯通了,能無限走了。
#include<bits/stdc++.h>
using namespace std;
char s[1505][1505];
int f[1505][1505];
struct node
{
int x,y;
} st,vis[1505][1505];//vis 用來記錄第一次到這個點時的座標,然後比較第二次來的時候的座標
int xx[4]= {0,0,1,-1};
int yy[4]= {1,-1,0,0};
int n,m;
int bfs()
{
node c;
f[st.x][st.y]=1;
vis[st.x][st.y].x=st.x;
vis[st.x][st.y].y=st.y;
queue<node > q;
q.push(st);
while(!q.empty())
{
node d=q.front();
q.pop();
for(int i=0; i<4; i++)
{
int x=d.x+xx[i];
int y=d.y+yy[i];
node cc;
cc.x=x;
cc.y=y;
c.x=(x%n+n)%n;
c.y=(y%m+m)%m;
if(s[c.x][c.y]=='#') continue;
if(!f[c.x][c.y])
{
f[c.x][c.y]=1;
q.push(cc);//注意是cc
vis[c.x][c.y].x=x;
vis[c.x][c.y].y=y;
}
else
{
if((vis[c.x][c.y].x!=x)||(vis[c.x][c.y].y!=y))//第二次到的座標與第一次不同,true
{
return 1;
}
}
}
}
return 0;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
{
scanf("%s",s[i]);
for(int j=0; j<m; j++)
{
if(s[i][j]=='S')
{
st.x=i;
st.y=j;
s[i][j]='.';
}
}
}
if(bfs())
{
puts("Yes");
}
else
{
puts("No");
}
return 0;
}