from collections import deque H, W = map(int, input().split()) board = [list(input()) for _ in range(H)] n_move = [(-2, -1),(-2, 1),(-1, -2),(-1, 2),(1, -2),(1, 2),(2, -1),(2, 1)] b_move = [(-1, 1),(-1, -1),(1, 1),(1, -1)] n_reached = [[0 for _ in range(W)] for __ in range(H)] b_reached = [[0 for _ in range(W)] for __ in range(H)] for x in range(W): for y in range(H): if board[y][x] == 'S': start = (x, y) class Piece: def __init__(self, state, style, step): self.state = state self.style = style self.step = step def BFS(s): q = deque() q.append(Piece(s, 'knight', 0)) while q: current = q.popleft() x, y = current.state form = current.style count = current.step if board[y][x] == 'G': return count if form == 'knight': for j, k in n_move: nx, ny = x + j, y + k if 0 > nx or nx > W-1 or 0 > ny or ny > H-1: continue if n_reached[ny][nx] == 1: continue n_reached[ny][nx] = 1 if board[ny][nx] == 'R': nform = 'bishop' else: nform = 'knight' p = Piece((nx, ny), nform, count+1) q.append(p) else: for n, m in b_move: nx, ny = x + n, y + m if 0 > nx or nx > W-1 or 0 > ny or ny > H-1: continue if b_reached[ny][nx] == 1: continue b_reached[ny][nx] = 1 if board[ny][nx] == 'R': nform = 'knight' else: nform = 'bishop' p = Piece((nx, ny), nform, count+1) q.append(p) return -1 print(BFS(start))