from collections import deque h, w = map(int, input().split()) S = [input() for _ in range(h)] inf = 1 << 60 dist = [inf] * (h * w * 2) def f(i, j, t): return (i * w + j) * 2 + t directions = [] directions.append([]) for i in [-2, -1, 1, 2]: for j in [-2, -1, 1, 2]: if abs(i) != abs(j): directions[0].append((i, j)) directions.append(((1, 1), (1, -1), (-1, 1), (-1, -1))) for i in range(h): for j in range(w): if S[i][j] == "S": si = i sj = j elif S[i][j] == "G": gi = i gj = j queue = deque() dist[f(si, sj, 0)] = 0 queue.append((si, sj, 0)) while queue: i, j, t = queue.popleft() for di, dj in directions[t]: ni = i + di nj = j + dj if ni < 0 or ni >= h or nj < 0 or nj >= w: continue if S[ni][nj] == "R": nt = t ^ 1 else: nt = t if dist[f(ni, nj, nt)] == inf: dist[f(ni, nj, nt)] = dist[f(i, j, t)] + 1 queue.append((ni, nj, nt)) ans = min(dist[f(gi, gj, 0)], dist[f(gi, gj, 1)]) if ans == inf: ans = -1 print(ans)