```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ``` ```import Control.Applicative data Dir = N | S | W | E deriving (Show, Eq) type Cell = ((Int, Int), Int) main = print \$ comp 3 S [S,E,N] comp :: Int -> Dir -> [Dir] -> Maybe [Cell] comp i di ds = foldl (\s n -> itera s i n ds) (crea i di) [2..(i*i)] crea :: Int -> Dir -> Maybe [Cell] crea i d | d == N = put (Just []) (mid, 1) 1 | d == S = put (Just []) (mid, i) 1 | d == W = put (Just []) (1, mid) 1 | d == E = put (Just []) (i, mid) 1 where mid = div (i+1) 2 itera :: Maybe [Cell] -> Int -> Int -> [Dir] -> Maybe [Cell] itera s i n [da, db, dc] = put s c1 n <|> put s c2 n where curr = maybe undefined (fst . head) s c1 = move i db . move i da \$ curr c2 = move i dc \$ curr put :: Maybe [Cell] -> (Int, Int) -> Int -> Maybe [Cell] put s c i = liftA2 lookup (pure c) s >>= \l -> case l of Nothing -> (:) <\$> pure (c, i) <*> s _ -> Nothing move i d (x, y) = case d of N -> (x, bound \$ y-1) S -> (x, bound \$ y+1) W -> (bound \$ x-1, y) E -> (bound \$ x+1, y) where bound n | n == 0 = i | n > i = 1 | otherwise = n ```
 ```1 ``` ```Just [((2,1),9),((1,3),8),((3,2),7),((3,3),6),((2,2),5),((1,1),4),((1,2),3),((3,1),2),((2,3),1)] ```