Skip to content

Instantly share code, notes, and snippets.

@ddrone
Created October 14, 2015 08:36
Show Gist options
  • Save ddrone/9564318d51651f50e4a1 to your computer and use it in GitHub Desktop.
Save ddrone/9564318d51651f50e4a1 to your computer and use it in GitHub Desktop.
module Dfs where
import Control.Monad.State
import Data.IntMap (IntMap)
import Data.IntSet (IntSet)
import Data.Maybe (fromMaybe)
import qualified Data.IntMap as IntMap
import qualified Data.IntSet as IntSet
type Vertex = Int
type Graph = IntMap [Vertex]
dfs :: Vertex -> Vertex -> Graph -> Bool
dfs from to edges = evalState (dfsInner [from]) IntSet.empty
where
dfsInner :: [Vertex] -> State IntSet Bool
dfsInner [] = return False
dfsInner (hd : tl)
| hd == to = return True
| otherwise =
do modify (IntSet.insert hd)
currentVisited <- get
let nextToVisit = filter (not . flip IntSet.member currentVisited)
(fromMaybe [] (IntMap.lookup hd edges))
dfsInner (nextToVisit ++ tl)
testGraph1 :: Graph
testGraph1 = IntMap.fromList
[ (1, [2, 3])
, (2, [1, 3, 4])
, (3, [1, 2])
, (4, [2])
]
testGraph2 :: Graph
testGraph2 = IntMap.fromList
[ (1, [2, 3])
, (2, [1, 3])
, (3, [1, 2])
, (4, [])
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment