mirror of
https://codeberg.org/JasterV/word-ladder.hs.git
synced 2026-04-27 02:15:44 +00:00
refactor dfsSearch
This commit is contained in:
parent
31f747dd84
commit
d9621f7d55
1 changed files with 16 additions and 17 deletions
35
src/Graph.hs
35
src/Graph.hs
|
|
@ -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'
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue