Created
November 13, 2014 10:02
-
-
Save LukaHorvat/ef810a33ca8045e2c8f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Graph = Vector [Int] | |
data BfsState = BfsState { queue :: Seq [Int] | |
, visited :: Set Int } | |
pop :: MaybeT (State BfsState) [Int] | |
pop = do | |
(x :< xs) <- viewl <$> gets queue | |
modify $ \y -> y { queue = xs } | |
return x | |
push :: [Int] -> MaybeT (State BfsState) () | |
push x = do q <- gets queue | |
modify $ \y -> y { queue = q |> x } | |
visit :: Int -> MaybeT (State BfsState) () | |
visit x = do v <- gets visited | |
modify $ \y -> y { visited = Set.insert x v } | |
bfs :: Int -> Int -> Graph -> Maybe [Int] | |
bfs start end g = evalState (runMaybeT loop') (BfsState (Seq.empty |> [start]) Set.empty) where | |
loop' = do | |
join $ guard . not . Seq.null <$> gets queue --If queue empty, treminate | |
(c : path) <- pop | |
isVis <- Set.member c <$> gets visited | |
if c == end then return $ c : path | |
else if isVis then loop' | |
else do visit c | |
forM_ (map (: c : path) (g ! c)) push | |
loop' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment