import java.util.ArrayDeque; import java.util.Arrays; import java.util.Scanner; public class Yuki367 { static Scanner sc = new Scanner(System.in); static int[] nX = { -2, -2, -1, -1, 1, 1, 2, 2 }; static int[] nY = { -1, 1, -2, 2, -2, 2, -1, 1 }; static int[] bX = { -1, -1, 1, 1 }; static int[] bY = { -1, 1, -1, 1 }; public static void main(String[] args) { int H, W; H = sc.nextInt(); W = sc.nextInt(); sc.nextLine(); boolean[][][] is = new boolean[2][H][W]; for (int i = 0; i < 2; i++) { for (int j = 0; j < H; j++) { Arrays.fill(is[i][j], false); } } int[] start = new int[2]; String[] S = new String[H]; for (int i = 0; i < H; i++) { S[i] = sc.nextLine(); for (int j = 0; j < W; j++) { if (S[i].charAt(j) == 'S') { start[0] = j; start[1] = i; } } } ArrayDeque q = new ArrayDeque<>(); q.add(new Now(start[0], start[1], 0, true)); while (!q.isEmpty()) { Now n = q.poll(); boolean f = n.knightFlag; int nowStep = n.step + 1; if (f) { for (int i = 0; i < nX.length; i++) { int x = n.x + nX[i]; int y = n.y + nY[i]; if (x < 0 || x >= W) continue; if (y < 0 || y >= H) continue; if (is[1][y][x]) continue; is[1][y][x] = true; if (S[y].charAt(x) == 'G') { System.out.println(nowStep); return; } if (S[y].charAt(x) == 'R') { q.add(new Now(x, y, nowStep, !f)); } else { q.add(new Now(x, y, nowStep, f)); } } } else { for (int i = 0; i < bX.length; i++) { int x = n.x + bX[i]; int y = n.y + bY[i]; if (x < 0 || x >= W) continue; if (y < 0 || y >= H) continue; if (is[0][y][x]) continue; is[0][y][x] = true; if (S[y].charAt(x) == 'G') { System.out.println(nowStep); return; } if (S[y].charAt(x) == 'R') { q.add(new Now(x, y, nowStep, !f)); } else { q.add(new Now(x, y, nowStep, f)); } } } } System.out.println(-1); } public static class Now { int x; int y; int step; boolean knightFlag; Now(int x, int y, int step, boolean f) { this.x = x; this.y = y; this.step = step; this.knightFlag = f; } } }