|
| 1 | +import qualified Data.Set as Set |
| 2 | +import qualified Data.Graph as Graph |
| 3 | +import Data.List (sort, group) |
| 4 | +import Data.Maybe (fromJust) |
| 5 | +import Data.Tuple (swap) |
| 6 | + |
| 7 | +type V = Graph.Vertex |
| 8 | +type N = String |
| 9 | + |
| 10 | +parseInput = Graph.graphFromEdges |
| 11 | + . group'' |
| 12 | + . sort |
| 13 | + . concat |
| 14 | + . sequence [id, map swap] |
| 15 | + . map (\x -> let (l,(_:r)) = break (=='-') x in (l, r)) |
| 16 | + . lines |
| 17 | + where |
| 18 | + group' :: N -> [N] -> [(N, N)] -> [((), N, [N])] |
| 19 | + group' k v [] = [((), k, v)] |
| 20 | + group' k v ((k',v'):l) | k == k' = group' k (v':v) l |
| 21 | + | k /= k' = ((), k, v) : group' k' [v'] l |
| 22 | + group'' :: [(N, N)] -> [((), N, [N])] |
| 23 | + group'' ((k, v):l) = group' k [v] l |
| 24 | + |
| 25 | +visit :: (V -> (N, [N])) -> (N -> Maybe V) -> V -> V -> V -> Bool -> Set.Set V -> [[V]] |
| 26 | +visit nfv vfk current start end twice visited |
| 27 | + = map (current:) $ foldMap (visitNode) nodes' |
| 28 | + where |
| 29 | + (curr, nodes) = nfv current |
| 30 | + nodes' = map (fromJust . vfk) nodes |
| 31 | + visitNode :: V -> [[V]] |
| 32 | + visitNode node |
| 33 | + | node == end = [[end]] |
| 34 | + | Set.member node visited && (twice' || node == start) = [] |
| 35 | + | otherwise = visit nfv vfk node start end twice' insert |
| 36 | + insert | small = Set.insert current visited |
| 37 | + | otherwise = visited |
| 38 | + small = "a" <= curr && curr <= "z" |
| 39 | + twice' = twice || Set.member current visited |
| 40 | + |
| 41 | +main = readFile "input.txt" |
| 42 | + >>= \x -> let (graph, nodeFromVertex, vertexFromKey) = parseInput x |
| 43 | + nfv = (\((), x, y) -> (x, y)) . nodeFromVertex |
| 44 | + vfk = vertexFromKey |
| 45 | + start = fromJust $ vfk "start" |
| 46 | + end = fromJust $ vfk "end" |
| 47 | + in print $ length |
| 48 | + $ visit nfv vfk start start end False Set.empty |
| 49 | + |
| 50 | +-- Debugging functions |
| 51 | + |
| 52 | +printPaths nfv = mapM_ (putStrLn . pathToString nfv) |
| 53 | + |
| 54 | +pathToString nfv = tail . foldr ((++) . (',':)) "" . map f |
| 55 | + where f = (\(_, l, _) -> l) . nfv |
0 commit comments