[Haskell] DFS与BFS

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)
                                               (adjacent g c))
                                        (c:vis)

参考

Algorithms: A Functional Programming Approach
Stack
Queue
Graph - 邻接表
Graph - 邻接矩阵

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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