local h, w = io.read("*n", "*n", "*l") local map = {} local inf = 1000000007 local len = {} local spos, gpos = 0, 0 for i = 1, h do local s = io.read() for j = 1, w do local ss = s:sub(j, j) local idx = (i - 1) * w + j map[idx] = false if ss == "S" then spos = idx elseif ss == "G" then gpos = idx elseif ss == "R" then map[idx] = true end end end for i = 1, h * w * 2 do len[i] = inf end local taskstate = {} for i = 1, h * w * 2 do taskstate[i] = false end local tasks = {} local tasknum = 0 local done = 0 local tasklim = h * w * 2 local function addtask(mixidx) if not taskstate[mixidx] then taskstate[mixidx] = true tasknum = tasknum + 1 local taskidx = tasknum % tasklim if taskidx == 0 then taskidx = tasklim end tasks[taskidx] = mixidx end end local function walk(src, dst, knight) local mixsrc = src if knight then mixsrc = mixsrc + h * w end local mixdst = dst if knight and not map[dst] then mixdst = mixdst + h * w elseif not knight and map[dst] then mixdst = mixdst + h * w end if len[mixsrc] + 1 < len[mixdst] then len[mixdst] = len[mixsrc] + 1 addtask(mixdst) end end len[spos + h * w] = 0 addtask(spos + h * w) while done < tasknum do done = done + 1 local taskidx = done % tasklim if taskidx == 0 then taskidx = tasklim end local mixidx = tasks[taskidx] taskstate[mixidx] = false local knight = h * w < mixidx local idx = mixidx if knight then idx = idx - h * w end if knight then if 2 * w < idx then if 1 < w then if idx % w ~= 0 then walk(idx, idx + 1 - w - w, true) end if idx % w ~= 1 then walk(idx, idx - 1 - w - w, true) end end end if idx <= (h - 2) * w then if 1 < w then if idx % w ~= 0 then walk(idx, idx + 1 + w + w, true) end if idx % w ~= 1 then walk(idx, idx - 1 + w + w, true) end end end if w < idx then if 2 < w then if idx % w ~= 0 and idx % w ~= (w - 1) then walk(idx, idx + 2 - w, true) end if idx % w ~= 1 and idx % w ~= 2 then walk(idx, idx - 2 - w, true) end end end if idx <= (h - 1) * w then if 2 < w then if idx % w ~= 0 and idx % w ~= (w - 1) then walk(idx, idx + 2 + w, true) end if idx % w ~= 1 and idx % w ~= 2 then walk(idx, idx - 2 + w, true) end end end else if w < idx then if 1 < w then if idx % w ~= 0 then walk(idx, idx + 1 - w, false) end if idx % w ~= 1 then walk(idx, idx - 1 - w, false) end end end if idx <= (h - 1) * w then if 1 < w then if idx % w ~= 0 then walk(idx, idx + 1 + w, false) end if idx % w ~= 1 then walk(idx, idx - 1 + w, false) end end end end end local ret = math.min(len[gpos], len[gpos + h * w]) print(inf <= ret and -1 or ret)