传送门:戳我(*^▽^*)
思路:一开始可能会考虑3*3个原图能确定,但是有下图的情况(标红色的是不同的小拼图同一个相对位置):
那么显然是不止3*3的,我们画了图能发现,如果原图里的某个位置,能走到另一个小拼图里同样的相对位置,例如像上图中红点那样,那么说明可以开始循环,也就是说这个倒霉孩子可以无限绕在迷宫里了。于是可以存一下原图里每个位置在别的小拼图里一样的相对位置里出现的,那个小地图里这个点的坐标,如果下一次发现要存的坐标和之前走过的不一样,那说明可以这个位置可以在两个小拼图里走,那就是ok的了。
代码:
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#include<map>
#include<vector>
#include<set>
#include<queue>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxv = 1515;
struct node
{
int x, y;
node(int _a = 0, int _b = 0) :x(_a), y(_b) {}
};
node st;
node in[maxv][maxv];
char mp[maxv][maxv];
int vis[maxv][maxv], n, m, dr[4][2] = { 0,1,0,-1,1,0,-1,0 };
int bfs()
{
queue<node > q;
vis[st.x][st.y] = 1;
in[st.x][st.y].x = st.x;
in[st.x][st.y].y = st.y;
q.push(st);
while (!q.empty())
{
node now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = now.x + dr[i][0];
int ny = now.y + dr[i][1];
int mpx = (nx%n + n) % n;
int mpy = (ny%m + m) % m;
if (mp[mpx][mpy] == '#')
continue;
if (vis[mpx][mpy])
{
if (nx != in[mpx][mpy].x || ny != in[mpx][mpy].y)
{
return 1;
}
}
else
{
q.push(node{ nx,ny });
vis[mpx][mpy] = 1;
in[mpx][mpy].x = nx;
in[mpx][mpy].y = ny;
}
}
}
return 0;
}
int main()
{
std::ios::sync_with_stdio(false);
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++)
{
scanf("%s", mp[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (mp[i][j] == 'S')
{
st.x = i;
st.y = j;
break;
}
}
}
int ans = bfs();
printf("%s\n", ans == 1 ? "Yes" : "No");
return 0;
}