From 6d5f5c7910d285ae7660c09fe681e0194ecb1bba Mon Sep 17 00:00:00 2001 From: Quinten Kock Date: Mon, 12 Dec 2022 06:44:18 +0100 Subject: [PATCH] day 12 part 2: invert the search --- 2022/day12.hs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/2022/day12.hs b/2022/day12.hs index 7d32a40..574d65d 100644 --- a/2022/day12.hs +++ b/2022/day12.hs @@ -17,7 +17,7 @@ bfs heightmap ((q@(x,y), dist):queue) visited = if usable where current = heightmap A.! q inRange (x,y) = let (bx, by) = snd (A.bounds heightmap) in x >= 0 && x <= bx && y >= 0 && y <= by - reachable coord = inRange coord && (heightmap A.! coord) <= current + 1 + reachable coord = inRange coord && (heightmap A.! coord) >= current - 1 neighs = filter reachable [(x+1, y), (x-1, y), (x, y+1), (x, y-1)] usable = case M.lookup q visited of Nothing -> True @@ -36,7 +36,7 @@ findIndex2 f xss = listToMaybe xs2 where xs2 = mapMaybe (uncurry augment) xs augment a (Just b) = Just (a,b) augment a Nothing = Nothing - + main = do m <- lines <$> getContents @@ -44,11 +44,13 @@ main = do let target = fromJust $ findIndex2 (=='E') m let heightmap = A.listArray ((0,0), (length m - 1, length (head m) - 1)) (concatMap (map toHeight) m) - print heightmap - let final = bfs heightmap [(start, 0)] M.empty + let final = bfs heightmap [(target, 0)] M.empty - print $ final M.! target + putStr "part 1: " + print $ final M.! start - - pure () \ No newline at end of file + putStr "part 2: " + let starts = map fst $ filter (\x -> snd x == toHeight 'a') (A.assocs heightmap) + let dists = mapMaybe (`M.lookup` final) starts + print $ minimum dists