using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using System.Linq; public class Program { static private int H, W; static private string[] S; static int[] KnightNextX = new int[] { -2, -2, -1, -1, 1, 1, 2, 2 }; static int[] KnightNextY = new int[] { -1, 1, -2, 2, -2, 2, -1, 1 }; static int[] BishopNextX = new int[] { -1, -1, 1, 1 }; static int[] BishopNextY = new int[] { 1, -1, 1, -1 }; static int Sy, Sx, Gx, Gy; static void Scan() { string[] line = Console.ReadLine().Split(' '); H = int.Parse(line[0]); W = int.Parse(line[1]); S = new string[H]; for (int i = 0; i < H; i++) { S[i] = Console.ReadLine(); } } public static void Main(string[] args) { Scan(); int[,] K = new int[H, W]; int[,] B = new int[H, W]; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { K[i, j] = int.MaxValue; B[i, j] = int.MaxValue; } } SearchSG(); K[Sy, Sx] = 0; var q = new Queue
(); q.Enqueue(new P(Sy, Sx, 1)); while (q.Count > 0) { var p = q.Dequeue(); if (p.Type == 1) { for (int i = 0; i < 8; i++) { int nextY = p.Y + KnightNextY[i]; int nextX = p.X + KnightNextX[i]; if (nextX < 0 || nextY < 0) continue; if (nextX >= W || nextY >= H) continue; if (S[nextY][nextX] == 'R') { if (B[nextY, nextX] != int.MaxValue) continue; q.Enqueue(new P(nextY, nextX, -1)); B[nextY, nextX] = K[p.Y, p.X] + 1; } else { if (K[nextY, nextX] != int.MaxValue) continue; q.Enqueue(new P(nextY, nextX, 1)); K[nextY, nextX] = K[p.Y, p.X] + 1; } } } else { for (int i = 0; i < 4; i++) { int nextY = p.Y + BishopNextY[i]; int nextX = p.X + BishopNextX[i]; if (nextX < 0 || nextY < 0) continue; if (nextX >= W || nextY >= H) continue; if (S[nextY][nextX] == 'R') { if (K[nextY, nextX] != int.MaxValue) continue; K[nextY, nextX] = B[p.Y, p.X] + 1; q.Enqueue(new P(nextY, nextX, 1)); } else { if (B[nextY, nextX] != int.MaxValue) continue; q.Enqueue(new P(nextY, nextX, -1)); B[nextY, nextX] = B[p.Y, p.X] + 1; } } } } if(K[Gy,Gx] == int.MaxValue&&B[Gy,Gx] == int.MaxValue) { Console.WriteLine(-1); return; } else { Console.WriteLine(Math.Min(K[Gy, Gx], B[Gy, Gx])); } } private static void SearchSG() { for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (S[i][j] == 'S') { Sy = i; Sx = j; } if(S[i][j] == 'G') { Gy = i; Gx = j; } } } } } struct P { public int Y, X; //1 K, -1 B public int Type; public P(int y, int x, int type) { Y = y; X = x; Type = type; } }