#!/usr/bin/env pypy3 import collections import itertools DS_KNIGHT = [(1, 2), (-1, -2), (1, -2), (-1, 2), (2, 1), (-2, -1), (2, -1), (-2, 1)] DS_MB = [(1, 1), (-1, -1), (1, -1), (-1, 1)] INF = 10 ** 8 Position = collections.namedtuple("Position", "r c") Status = collections.namedtuple("Status", "is_knight position") def min_num_of_operations(height, width, board, start, goal): s_start = Status(True, start) dist = collections.defaultdict(lambda: INF) dist[s_start] = 0 q = collections.deque() q.append(s_start) while q: s0 = q.popleft() if s0.position == goal: break for dr, dc in (DS_KNIGHT if s0.is_knight else DS_MB): p = Position(s0.position.r + dr, s0.position.c + dc) if p.r < 0 or p.r >= height: continue elif p.c < 0 or p.c >= width: continue elif dist[Status(True, p)] >= INF or dist[Status(False, p)] >= INF: new_class = not s0.is_knight if board[p.r][p.c] == "R" else s0.is_knight s = Status(new_class, p) dist[s] = dist[s0] + 1 q.append(s) return min(dist[Status(True, goal)], dist[Status(False, goal)]) def main(): height, width = map(int, input().split()) board = [input() for _ in range(height)] start = None goal = None for r, c in itertools.product(range(height), range(width)): if board[r][c] == "S": start = Position(r, c) elif board[r][c] == "G": goal = Position(r, c) if (start is not None) and (goal is not None): break answer = min_num_of_operations(height, width, board, start, goal) print(answer if answer < INF else -1) if __name__ == '__main__': main()