import heapq H,W = map(int,input().split()) s = [input() for i in range(H)] sx,sy,gx,gy = 0,0,0,0 for i in range(H): for j in range(W): if s[i][j] == 'S': sy = i sx = j elif s[i][j] == 'G': gy = i gx = j used = [[[False for k in range(2)]for j in range(W)] for i in range(H)] find = False adx = [2,-2,2,-2,1,-1,1,-1] ady = [1,1,-1,-1,2,2,-2,-2] bdx = [1,1,-1,-1] bdy = [1,-1,1,-1] q = [[0, sy, sx, True]] used[sy][sx][0] = True while q and (not find): ele = heapq.heappop(q) c = ele[0] y = ele[1] x = ele[2] isKnight = ele[3] cdy = bdy cdx = bdx if isKnight: cdy = ady cdx = adx for i in range(len(cdx)): ny = cdy[i] + y nx = cdx[i] + x mode = isKnight if ny < 0 or nx < 0 or ny >= H or nx >= W:continue if isKnight: if used[ny][nx][0]:continue else: if used[ny][nx][1]:continue if ny == gy and nx == gx: print(c + 1) find = True break if s[ny][nx] == 'R': mode = (not mode) if isKnight: used[ny][nx][0] = True else: used[ny][nx][1] = True heapq.heappush(q, [c + 1, ny, nx, mode]) if not find: print (-1)