from collections import deque def list3(a, b, c, *, val=0): return [[[val] * c for _ in range(b)] for _ in range(a)] 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() used = list3(H, W, 2, val=False) while q: r, c, step, piece = q.popleft() # if (r, c, piece) in used: continue # used.add((r, c, piece)) if used[r][c][piece]: continue used[r][c][piece] = True 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 if used[nr][nc][np]: continue q.append((nr, nc, step+1, np)) else: print(-1)