from collections import deque H, W = map(int, input().split()) G = [input() for _ in range(H)] def find(c) -> tuple[int, int]: for i in range(H): for j in range(W): if G[i][j] == c: return i, j assert False def move_knight(r, c): res = [] for dr, dc in [(-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)]: nr = r + dr nc = c + dc if not (0 <= nr < H and 0 <= nc < W): continue res.append((nr, nc)) return res def move_bishop(r, c): res = [] for dr, dc in [(-1, 1), (1, 1), (1, -1), (-1, -1)]: nr = r + dr nc = c + dc if not (0 <= nr < H and 0 <= nc < W): continue res.append((nr, nc)) return res KNIGHT = 0 BISHOP = 1 start = find('S') q = deque([(start[0], start[1], 0, 0)]) used = set() while q: r, c, step, piece = q.popleft() if (r, c, piece) in used: continue used.add((r, c, piece)) if G[r][c] == 'G': print(step) break movefn = move_knight if piece == 0 else move_bishop for nr, nc in movefn(r, c): np = piece if G[nr][nc] == 'R': np ^= 1 if (nr, nc, np) in used: continue q.append((nr, nc, step+1, np)) else: print(-1)