from collections import deque import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) move = (( (1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1) ), ( (-1, -1), (1, 1), (1, -1), (-1, 1) )) H, W = map(int, input().split()) G = [input().rstrip() for _ in range(H)] for i in range(H): for j in range(W): if G[i][j] == "S": sx, sy = i, j if G[i][j] == "G": gx, gy = i, j inf = 10**9 dist = [[[inf] * 2 for _ in range(W)] for _ in range(H)] dist[sx][sy][0] = 0 que = deque([(sx, sy, 0)]) while que: x, y, f = que.popleft() d = dist[x][y][f] for dx, dy in move[f]: nx = x + dx ny = y + dy if 0 <= nx < H and 0 <= ny < W: nf = f if G[nx][ny] == "R": nf = f ^ 1 if dist[nx][ny][nf] > d + 1: dist[nx][ny][nf] = d + 1 que.append((nx, ny, nf)) ans = min(dist[gx][gy][0], dist[gx][gy][1]) if ans >= inf: ans = -1 print(ans)