Skip to content

Instantly share code, notes, and snippets.

@LukaHorvat
Created November 13, 2014 10:01
Show Gist options
  • Save LukaHorvat/e169fdfd87d0d4bc90d3 to your computer and use it in GitHub Desktop.
Save LukaHorvat/e169fdfd87d0d4bc90d3 to your computer and use it in GitHub Desktop.
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