from queue import Queue dx = [[-2, -2, -1, 1, 2, 2, 1, -1], [-1, -1, 1, 1]] dy = [[-1, 1, 2, 2, 1, -1, -2, -2], [-1, 1, 1, -1]] h, w = map(int, input().split()) s = [input() for i in range(h)] sx, sy, gx, gy = [-1, -1, -1, -1] for i, line in enumerate(s): for j, c in enumerate(line): if c == "S": sx, sy = i, j elif c == "G": gx, gy = i, j dist = [[ [-1, -1] for j in range(w)] for i in range(h)] q = Queue() dist[sx][sy][0] = 0 q.put((sx, sy, 0)) while not q.empty(): x, y, d = q.get() for i in range(len(dx[d])): nx, ny = x + dx[d][i], y + dy[d][i] if nx < 0 or h <= nx or ny < 0 or w <= ny: continue nd = d ^ (1 if s[nx][ny] == "R" else 0) if dist[nx][ny][nd] == -1: dist[nx][ny][nd] = dist[x][y][d] + 1 q.put((nx, ny, nd)) res = -1 if dist[gx][gy][0] == -1: res = dist[gx][gy][1] elif dist[gx][gy][1] == -1: res = dist[gx][gy][0] else: res = min(dist[gx][gy]) print(res)