Code:
#include <cstdio>
#include <map>
#include <queue>
#define N 10005
using namespace std;
const int xx[4] = {-1, 1, 0, 0};
const int yy[4] = {0, 0, -1, 1};
int n, m;
char ch;
int be_x, be_y;
bool can[N][N];
bool vis[N][N];
int vis_x[N][N];
int vis_y[N][N];
struct Node {
int x, y;
Node(int _x, int _y) {
x = _x;
y = _y;
}
};
queue <Node> q;
bool bfs(int be_x, int be_y) {
while(!q.empty())
q.pop();
vis[be_x][be_y] = true;
vis_x[be_x][be_y] = be_x;
vis_y[be_x][be_y] = be_y;
q.push(Node(be_x, be_y));
while(!q.empty()) {
Node top = q.front();
q.pop();
for(int i = 0; i < 4; ++i) {
int x1 = top.x + xx[i];
int y1 = top.y + yy[i];
int x2, y2;
if(x1 >= 0)
x2 = x1 % n;
else
x2 = (x1 + ((0 - x1) / n + 1) * n) % n;
if(y1 >= 0)
y2 = y1 % m;
else
y2 = (y1 + ((0 - y1) / m + 1) * m) % m;
if(!can[x2][y2])
continue;
if(vis[x2][y2] && (vis_x[x2][y2] != x1 || vis_y[x2][y2] != y1))
return true;
if(vis[x2][y2])
continue;
vis[x2][y2] = true;
vis_x[x2][y2] = x1;
vis_y[x2][y2] = y1;
q.push(Node(x1, y1));
}
}
return false;
}
int main() {
while(scanf("%d%d", &n, &m) != EOF) {
for(int i = 0; i < n; ++i) {
scanf("\n");
for(int j = 0; j < m; ++j) {
vis[i][j] = false;
scanf("%c", &ch);
if(ch == '.')
can[i][j] = true;
else if(ch == '#')
can[i][j] = false;
else {
can[i][j] = true;
be_x = i, be_y = j;
}
}
}
puts(bfs(be_x, be_y) ? "Yes" : "No");
}
return 0;
}