import Control.Applicative import Data.List import Data.Array.Unboxed import qualified Data.Sequence import qualified Data.Set import Data.Maybe import Debug.Trace -- 2-stack queue -- partial persistent として使うのであれば各操作 amortized O(1) data Queue a = Node [a] [a] queueEmpty = Node [] [] queueNull (Node [] []) = True queueNull (Node _ _) = False enqueue x (Node s1 s2) = Node s1 (x : s2) dequeue (Node [] s2) = dequeue (Node (reverse s2) []) dequeue (Node (s:s1) s2) = (s, Node s1 s2) main = do [h, w] <- map read . words <$> getLine :: IO [Int] ss <- concat . map (\(i, s) -> zip (zip (repeat i) [1..]) s) . zip [1..] . lines <$> getContents :: IO [((Int, Int), Char)] let grid = array ((1, 1), (h, w)) ss :: UArray (Int, Int) Char let (y, x) = startPoint grid print $ bfs grid h w (enqueue (y, x, 0, 0) queueEmpty) (Data.Set.fromList [(y, x, 0)]) startPoint = fst . fromJust . find (\(i, x) -> x == 'S') . Data.Array.Unboxed.assocs bfs :: UArray (Int, Int) Char -> Int -> Int -> Queue (Int, Int, Int, Int) -> Data.Set.Set (Int, Int, Int) -> Int bfs grid h w q vis | queueNull q = -1 | grid ! (y, x) == 'G' = turn | otherwise = let inside y x = 1 <= y && y <= h && 1 <= x && x <= w dd = if t == 0 then [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] else [(-1, -1), (-1, 1), (1, -1), (1, 1)] npos = [(y + dy, x + dx) | (dy, dx) <- dd, inside (y + dy) (x + dx)] nst = [(ny, nx, nt) | (ny, nx) <- npos, nt <- [if grid ! (ny, nx) == 'R' then 1 - t else t], Data.Set.notMember (ny, nx, nt) vis] nstate = [(ny, nx, nt, turn + 1) | (ny, nx, nt) <- nst] nvis = foldr Data.Set.insert vis nst nque = foldr enqueue que nstate in bfs grid h w nque nvis where ((y, x, t, turn), que) = dequeue q