#!/usr/bin/ python3.8 import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import itertools from collections import deque H, W = map(int, readline().split()) S = ''.join(read().decode().split()) start = S.index('S') goal = S.index('G') N = H * W Knight = ((2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)) Bishop = ((1, 1), (-1, 1), (-1, -1), (1, -1)) # 0 <= i < N:knightで出発 # N <= i < 2N:bishopで出発 graph = [[] for _ in range(N + N)] for x, y in itertools.product(range(H), range(W)): for dx, dy in Knight: x1 = x + dx y1 = y + dy if not ((0 <= x1 < H) and (0 <= y1 < W)): continue i = x * W + y j = x1 * W + y1 if S[j] == 'R': j += N graph[i].append(j) for dx, dy in Bishop: x1 = x + dx y1 = y + dy if not ((0 <= x1 < H) and (0 <= y1 < W)): continue i = x * W + y + N j = x1 * W + y1 if S[j] != 'R': j += N graph[i].append(j) INF = 10 ** 6 dist = [INF] * (N + N) dist[start] = 0 q = deque([start]) while q: v = q.popleft() dw = dist[v] + 1 for w in graph[v]: if dist[w] <= dw: continue dist[w] = dw q.append(w) answer = min(dist[goal], dist[goal + N]) if answer == INF: answer = -1 print(answer)