import sys ni = lambda :int(input()) na = lambda :list(map(int,input().split())) yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES") no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO") ##################################################################### h, w = na() s = [input() for i in range(h)] from collections import deque for i in range(h): for j in range(w): if s[i][j] == "S": sx, sy = i, j elif s[i][j] == "G": gx, gy = i, j def f(x, y, z): return x * 3 * w + y * 3 + z dist = [-1] * (h * w * 3) dq = deque([(sx, sy, 0)]) dist[f(sx, sy, 0)] = 0 while dq: x, y, i = dq.popleft() if i == 0: for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]: nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if s[nx][ny] != "#" and dist[f(nx, ny, 0)] == -1: dist[f(nx, ny, 0)] = dist[f(x, y, 0)] + 1 dq.append((nx, ny, 0)) for dx, dy in [[1, 0], [-1, 0]]: nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if dist[f(nx, ny, 1)] == -1: dist[f(nx, ny, 1)] = dist[f(x, y, 0)] + 1 dq.append((nx, ny, 1)) for dx, dy in [[0, 1], [0, -1]]: nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if dist[f(nx, ny, 2)] == -1: dist[f(nx, ny, 2)] = dist[f(x, y, 0)] + 1 dq.append((nx, ny, 2)) elif i == 1: for dx, dy in [[0, 1], [0, -1]]: nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if dist[f(nx, ny, 1)] == -1: dist[f(nx, ny, 1)] = dist[f(x, y, i)] + 1 dq.append((nx, ny, 1)) if dist[f(x, y, 0)] == -1 and s[x][y] != "#": dist[f(x, y, 0)] = dist[f(x, y, i)] + 1 dq.append((x, y, 0)) if dist[f(x, y, 2)] == -1: dist[f(x, y, 2)] = dist[f(x, y, i)] + 1 dq.append((x, y, 2)) else: for dx, dy in [[1, 0], [-1, 0]]: nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if dist[f(nx, ny, 2)] == -1: dist[f(nx, ny, 2)] = dist[f(x, y, i)] + 1 dq.append((nx, ny, 2)) if dist[f(x, y, 0)] == -1 and s[x][y] != "#": dist[f(x, y, 0)] = dist[f(x, y, i)] + 1 dq.append((x, y, 0)) if dist[f(x, y, 1)] == -1: dist[f(x, y, 1)] = dist[f(x, y, i)] + 1 dq.append((x, y, 1)) # for i in range(h): # print([dist[f(i, j, 0)] for j in range(w)]) # print() # for i in range(h): # print([dist[f(i, j, 1)] for j in range(w)]) # print() # for i in range(h): # print([dist[f(i, j, 2)] for j in range(w)]) print(dist[f(gx, gy, 0)])