import java.io.*; import java.util.*; public class Main_yukicoder367 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Printer pr = new Printer(System.out); int h = sc.nextInt(); int w = sc.nextInt(); char[][] ban = new char[h][]; for (int i = 0; i < h; i++) { ban[i] = sc.next().toCharArray(); } int sx = 0; int sy = 0; int gx = 0; int gy = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (ban[i][j] == 'S') { sx = j; sy = i; } if (ban[i][j] == 'G') { gx = j; gy = i; } } } int[] dxn = {2, 2, 1, 1, -1, -1, -2, -2}; int[] dyn = {1, -1, 2, -2, 2, -2, 1, -1}; int[] dxb = {1, 1, -1, -1}; int[] dyb = {1, -1, 1, -1}; Queue qx = new ArrayDeque<>(); Queue qy = new ArrayDeque<>(); Queue qs = new ArrayDeque<>(); Queue qc = new ArrayDeque<>(); qx.add(sx); qy.add(sy); qs.add(0); qc.add(0); boolean[][][] used = new boolean[2][h][w]; used[0][sy][sx] = true; int res = 0; while (!qx.isEmpty()) { int x = qx.remove(); int y = qy.remove(); int s = qs.remove(); int cnt = qc.remove(); if (x == gx && y == gy) { res = cnt; break; } if (s == 0) { for (int i = 0; i < dxn.length; i++) { int nx = x + dxn[i]; int ny = y + dyn[i]; int ns = s; if (nx < 0 || nx >= w || ny < 0 || ny >= h) { continue; } if (ban[ny][nx] == 'R') { ns = (s + 1) % 2; } if (used[ns][ny][nx]) { continue; } used[ns][ny][nx] = true; qx.add(nx); qy.add(ny); qs.add(ns); qc.add(cnt + 1); } } else { for (int i = 0; i < dxb.length; i++) { int nx = x + dxb[i]; int ny = y + dyb[i]; int ns = s; if (nx < 0 || nx >= w || ny < 0 || ny >= h) { continue; } if (ban[ny][nx] == 'R') { ns = (ns + 1) % 2; } if (used[ns][ny][nx]) { continue; } used[ns][ny][nx] = true; qx.add(nx); qy.add(ny); qs.add(ns); qc.add(cnt + 1); } } } if (res == 0) { pr.println(-1); } else { pr.println(res); } pr.close(); sc.close(); } @SuppressWarnings("unused") private static class Scanner { BufferedReader br; Iterator it; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() throws RuntimeException { try { if (it == null || !it.hasNext()) { it = Arrays.asList(br.readLine().split(" ")).iterator(); } return it.next(); } catch (IOException e) { throw new IllegalStateException(); } } int nextInt() throws RuntimeException { return Integer.parseInt(next()); } long nextLong() throws RuntimeException { return Long.parseLong(next()); } float nextFloat() throws RuntimeException { return Float.parseFloat(next()); } double nextDouble() throws RuntimeException { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { // throw new IllegalStateException(); } } } private static class Printer extends PrintWriter { Printer(PrintStream out) { super(out); } } }