import Data.List import Data.Maybe type Position = (Int,Int) type Entry = (Maybe Int, Int) type MatrixMap = [(Position, Entry)] parse :: Int -> Int -> String -> MatrixMap parse x y []=[] parse x y ('\n':xs)=parse 0(y+1)xs parse x y ('S':xs)=((x,y),(Just 0,fromEnum 'a')):parse(x+1)y xs parse x y ('E':xs)=((x,y),(Nothing,fromEnum 'z')):parse(x+1)y xs parse x y (i:xs)=((x,y),(Nothing,fromEnum i)):parse(x+1)y xs parse2 x y []=[] parse2 x y ('\n':xs)=parse2 0(y+1)xs parse2 x y ('S':xs)=((x,y),(Nothing,fromEnum 'a')):parse2(x+1)y xs parse2 x y ('E':xs)=((x,y),(Just 0,fromEnum 'z')):parse2(x+1)y xs parse2 x y (i:xs)=((x,y),(Nothing,fromEnum i)):parse2(x+1)y xs s = f(0,0)'S' e = f(0,0)'E' f :: Position -> Char-> String -> Position f(x,y)i(h:t)|h==i=(x,y)|'\n'==h=f(0,y+1)i t|let=f(x+1,y)i t lookup2 i p = lookup i p >>= \x->pure(i, x) valuesSurrounding :: Position -> MatrixMap -> [(Position, Entry)] valuesSurrounding (x,y)pos|Just (Just d,h)<-lookup (x,y) pos = map (\(p,(_,i))->(p,(Just (d+1), i))) $ filter((==Nothing).fst.snd) $ filter((<=h+1).snd.snd) $ catMaybes $ map(`lookup2`pos) [(x,y-1),(x,y+1),(x+1,y),(x-1,y)] valuesSurrounding2 :: Position -> MatrixMap -> [(Position, Entry)] valuesSurrounding2 (x,y)pos|Just (Just d,h)<-lookup (x,y) pos = map (\(p,(_,i))->(p,(Just (d+1), i))) $ filter((==Nothing).fst.snd) $ filter((>=h-1).snd.snd) $ catMaybes $ map(`lookup2`pos) [(x,y-1),(x,y+1),(x+1,y),(x-1,y)] doStuff :: MatrixMap -> [(Position, Entry)] -> MatrixMap doStuff i [] = i doStuff i (x:t)|n<-valuesSurrounding (fst x) i=doStuff (foldr update i n) (t++n) doStuff2 :: MatrixMap -> [(Position, Entry)] -> MatrixMap doStuff2 i [] = i doStuff2 i (x:t)|n<-valuesSurrounding2 (fst x) i=doStuff2 (foldr update i n) (t++n) update :: (Position, Entry) -> MatrixMap -> MatrixMap update x m|Just entry<-lookup (fst x) m, Just idx<-elemIndex (fst x,entry) m,(h,c:t)<-splitAt idx m = h++x:t p1 f = do x <- readFile f let m = parse 0 0 x let Just start = lookup2 (s x) m let d = doStuff m [start] let end = lookup2 (e x) d print end p2 f = do x <- readFile f let m = parse2 0 0 x let Just start = lookup2 (e x) m let d = doStuff2 m [start] let (Just f, _) = head$sort$map snd$filter (\(p,(i,q))->q==97 && i /= Nothing) d print f main=p1 "day12long" >> p2 "day12long"