### 1. DFS

``````import Data.Ix
import Graph
import Stack

depthFirstSearch :: Ix a => a -> Graph a a -> [a]
depthFirstSearch start g = dfs [start] []
where
dfs [] vis = vis
dfs (c:cs) vis | elem c vis = dfs cs vis
| otherwise  = dfs ((adjacent g c) ++ cs) (vis ++ [c])

depthFirstSearch' :: Ix a => a -> Graph a a -> [a]
depthFirstSearch' start g = reverse \$ dfs [start] []
where
dfs [] vis = vis
dfs (c:cs) vis | elem c vis = dfs cs vis
| otherwise  = dfs ((adjacent g c) ++ cs) (c:vis)

depthFirstSearch'' :: Ix a => a -> Graph a a -> [a]
depthFirstSearch'' start g = reverse \$ dfs (push start emptyStack) []
where
dfs s vis | (stackEmpty s) = vis
| elem (top s) vis = dfs (pop s) vis
| otherwise = let c = top s
in
dfs (foldr push (pop s) (adjacent g c))
(c:vis)
``````

### 2. BFS

``````import Data.Ix
import Graph
import Queue

breadFirstSearch :: Ix a => a -> Graph a a -> [a]
breadFirstSearch start g = reverse (bfs (enqueue start emptyQueue) [])
where
bfs q vis | (queueEmpty q) = vis
| elem (front q) vis = bfs (dequeue q) vis
| otherwise = let c = front q
in
bfs (foldr enqueue
(dequeue q)
(c:vis)
``````

### 推荐阅读更多精彩内容

• 01 初看岩井俊二的《情书》觉得情节平淡无奇，甚至有些不知所云。当然，很大原因是因为鉴赏能力不够。再看下去，却觉得...
安步当车阅读 416评论 2 8
• 我常常会望着天空想，如果，如果有一天我真的能够回到从前，我会做什么，怎么做，能不能做到呢？而我又会遇到什么样的事，...
听雨随风阅读 19评论 0 0
• 首先，依照我现在的心情，这可能是一篇负能量的文章，如果你心情很好，请绕过它，心情很差，也请绕过它，不过也可能我们相...
最爱夏雨天阅读 69评论 0 0
• 日子过得飞快，10月已经过了三周，又到了每周总结的时间了，但是我还从来没有写到过1000字，每次都觉得词穷。 这周...
八月芳菲阅读 25评论 0 0
• 思 清风吹乱黑烟， 愁云落在眉间。 无奈无人甚解， 隐月怎不出现。 05.5.12 欢迎留下您的评论...... ...
清风隐月阅读 48评论 0 3