forked from ddhira123/Algorithms-HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfs.hs
More file actions
24 lines (19 loc) · 640 Bytes
/
dfs.hs
File metadata and controls
24 lines (19 loc) · 640 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import Data.List ((\\))
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
type Graph = Map.Map Int [Int]
graph :: Graph
graph = Map.fromAscList [
(0, [1, 2, 3]),
(1, [2]),
(2, [0]) ]
dfsHelper :: Graph -> [Int] -> [Int] -> [Int]
dfsHelper graph [] _ = []
dfsHelper graph (current:rest) visited = current:(dfsHelper graph (rest ++ toVisit) (current:visited))
where neighbors = Map.findWithDefault [] current graph
toVisit = neighbors \\ (rest ++ visited)
dfs :: Graph -> Int -> [Int]
dfs graph root = dfsHelper graph [root] []
main :: IO ()
main = do
putStrLn $ show $ dfs graph 0