refactor dfsSearch

This commit is contained in:
JasterV 2025-03-23 17:32:23 +01:00
commit d9621f7d55

View file

@ -119,25 +119,24 @@ type DfsSearchResult a = Either (DiGraph a) (Path a)
dfsSearch :: forall a. (Eq a) => DiGraph a -> a -> a -> Maybe (Path a) dfsSearch :: forall a. (Eq a) => DiGraph a -> a -> a -> Maybe (Path a)
dfsSearch initialGraph start end = dfsSearch initialGraph start end =
case dfsSearch' initialGraph start [] of case dfsSearch' initialGraph start of
Right path -> Just path Right path -> Just path
Left _ -> Nothing Left _ -> Nothing
where where
searchNeighbours :: [a] -> Path a -> DiGraph a -> DfsSearchResult a dfsSearch' :: DiGraph a -> a -> DfsSearchResult a
searchNeighbours [] _ graph = Left graph dfsSearch' graph node
searchNeighbours (x : xs) path graph = case dfsSearch' graph x path of | node == end = Right [node]
-- If a path was found, just return it
Right path' -> Right path'
-- If no path was found, keep searching on the updated graph
Left graph' -> searchNeighbours xs path graph'
dfsSearch' :: DiGraph a -> a -> [a] -> DfsSearchResult a
dfsSearch' graph node path
| not (hasNode graph node) = Left graph -- If already visited
| node == end = Right path'
| otherwise = | otherwise =
let neighbours = children node graph -- Get neighbouring nodes let graph' = deleteNode node graph -- Mark node as visited
graph' = deleteNode node graph -- Mark node as visited neighbours = children node graph -- Get neighbouring nodes
in searchNeighbours neighbours path' graph' in case searchNeighbours neighbours graph' of
where Right path -> Right (node : path)
path' = path ++ [node] -- New path Left graph'' -> Left graph''
searchNeighbours :: [a] -> DiGraph a -> DfsSearchResult a
searchNeighbours [] graph = Left graph
searchNeighbours (x : xs) graph = case dfsSearch' graph x of
-- If a path was found, just return it
Right path -> Right path
-- If no path was found, keep searching on the updated graph
Left graph' -> searchNeighbours xs graph'