import java.util.Arrays; import java.util.LinkedList; import java.util.Scanner; public class Main { public static long MOD = 1000000007; public static final int INF = Integer.MAX_VALUE / 2 - 1; public static boolean in_range(int x, int y, int W, int H){ return 0 <= x && x < W && 0 <= y && y < H; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int H = sc.nextInt(); final int W = sc.nextInt(); int sx = -1, sy = -1, gx = -1, gy = -1; boolean[][] is_red = new boolean[H][W]; for(int i = 0; i < H; i++){ final char[] ins = sc.next().toCharArray(); for(int j = 0; j < W; j++){ if(ins[j] == 'R'){ is_red[i][j] = true; }else if(ins[j] == 'S'){ sx = j; sy = i; }else if(ins[j] == 'G'){ gx = j; gy = i; } } } LinkedList queue = new LinkedList(); final int KNIGHT = 0, MINB = 1; int[][][] costs = new int[H][W][2]; for(int i = 0; i < H; i++){ for(int j = 0; j < W; j++){ costs[i][j][0] = INF; costs[i][j][1] = INF; } } costs[sy][sx][KNIGHT] = 0; queue.add(sx); queue.add(sy); queue.add(KNIGHT); while(!queue.isEmpty()){ final int x = queue.poll(); final int y = queue.poll(); final int type = queue.poll(); //System.out.println(x + " " + y + " " + (type == KNIGHT ? "N" : "B")); if(type == MINB){ for(int dy = -1; dy <= 1; dy++){ for(int dx = -1; dx <= 1; dx++){ if(dx == 0 && dy == 0){ continue; } if(Math.abs(dx) == 0 || Math.abs(dy) == 0){ continue; } final int nx = x + dx; final int ny = y + dy; if(!in_range(nx, ny, W, H)){ continue; } final int next_type = is_red[ny][nx] ? 1 - type : type; if(costs[ny][nx][next_type] <= costs[y][x][type] + 1){ continue; } costs[ny][nx][next_type] = costs[y][x][type] + 1; queue.add(nx); queue.add(ny); queue.add(next_type); } } }else{ for(int dy = -2; dy <= 2; dy++){ for(int dx = -2; dx <= 2; dx++){ if(Math.abs(dx) == Math.abs(dy)){ continue; } if(Math.min(Math.abs(dx), Math.abs(dy)) == 0){ continue; } final int nx = x + dx; final int ny = y + dy; if(!in_range(nx, ny, W, H)){ continue; } final int next_type = is_red[ny][nx] ? 1 - type : type; if(costs[ny][nx][next_type] <= costs[y][x][type] + 1){ continue; } costs[ny][nx][next_type] = costs[y][x][type] + 1; queue.add(nx); queue.add(ny); queue.add(next_type); } } } } final int min_cost = Math.min(costs[gy][gx][KNIGHT], costs[gy][gx][MINB]); System.out.println(min_cost >= INF ? -1 : min_cost); } }