#include #include #include #include #include using namespace std; int main() { vector> dx = {{1, -1, 1, -1, 2, -2, 2, -2}, {1, -1, 1, -1}}; vector> dy = {{2, 2, -2, -2, 1, 1, -1, -1}, {1, 1, -1, -1}}; int h, w; int count[500][500][2]; vector area; queue> q; cin >> h >> w; area.resize(h); for (int y = 0; y < h; ++y) { cin >> area[y]; for (int x = 0; x < w; ++x) { count[y][x][0] = count[y][x][1] = -1; if (area[y][x] == 'S') { count[y][x][0] = 0; q.push(vector{0, x, y}); } } } while (not q.empty()) { int s = q.front()[0]; int x = q.front()[1]; int y = q.front()[2]; q.pop(); for (size_t d = 0; d < dx[s].size(); ++d) { int nx = x + dx[s][d]; int ny = y + dy[s][d]; if (0 <= nx and nx < w and 0 <= ny and ny < h) { int ns = (area[ny][nx] == 'R'? 1 - s: s); if (count[ny][nx][ns] < 0) { count[ny][nx][ns] = count[y][x][s] + 1; q.push({ns, nx, ny}); } if (area[ny][nx] == 'G') { cout << count[y][x][s] + 1 << endl; return 0; } } } } cout << -1 << endl; return 0; }