import java.util.*; public class Main { static char[][] field; static int[][][] visited; static int h; static int w; public static void main (String[] args) { Scanner sc = new Scanner(System.in); h = sc.nextInt(); w = sc.nextInt(); field = new char[h][]; visited = new int[2][h][w]; int sh = 0; int sw = 0; int gh = 0; int gw = 0; for (int i = 0; i < h; i++) { Arrays.fill(visited[0][i], Integer.MAX_VALUE); Arrays.fill(visited[1][i], Integer.MAX_VALUE); field[i] = sc.next().toCharArray(); for (int j = 0; j < w; j++) { if (field[i][j] == 'S') { sh = i; sw = j; } else if (field[i][j] == 'G') { gh = i; gw = j; } } } search(0, sh, sw, 0); if (visited[0][gh][gw] == Integer.MAX_VALUE && visited[1][gh][gw] == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(Math.min(visited[0][gh][gw], visited[1][gh][gw])); } } static void search(int type, int hh, int ww, int count) { if (hh < 0 || ww < 0 || hh >= h || ww >= w) { return; } if (field[hh][ww] == 'R') { type = (type + 1) % 2; } if (visited[type][hh][ww] <= count) { return; } visited[type][hh][ww] = count; if (type == 0) { search(type, hh - 2, ww - 1, count + 1); search(type, hh - 1, ww - 2, count + 1); search(type, hh + 2, ww - 1, count + 1); search(type, hh + 1, ww - 2, count + 1); search(type, hh - 2, ww + 1, count + 1); search(type, hh - 1, ww + 2, count + 1); search(type, hh + 2, ww + 1, count + 1); search(type, hh + 1, ww + 2, count + 1); } else { search(type, hh - 1, ww - 1, count + 1); search(type, hh + 1, ww - 1, count + 1); search(type, hh - 1, ww + 1, count + 1); search(type, hh + 1, ww + 1, count + 1); } } }