美文网首页Haskell
[Haskell] 拓扑排序

[Haskell] 拓扑排序

作者: 何幻 | 来源:发表于2017-03-27 14:12 被阅读17次

1. 拓扑排序

import Data.Ix
import Graph

inDegree :: Ix a => Graph a a -> a -> Int
inDegree g n = length [t | v <- nodes g, t <- adjacent g v, n == t]

topologicalSort :: Ix a => Graph a a -> [a]
topologicalSort g = tsort [n | n <- nodes g, inDegree g n == 0] []
    where 
        tsort [] r = r 
        tsort (c:cs) vis | elem c vis = tsort cs vis 
                         | otherwise = tsort cs (c:(tsort (adjacent g c) vis))
                         

2. 用例

testGraph = mkGraph True (1, 6) 
                    [(1, 2, 0), (1, 3, 0), (1, 4, 0),
                     (3, 6, 0), (5, 4, 0), (6, 2, 0),
                     (6, 5, 0)]
                
testTopologicalSort = topologicalSort testGraph
-- [1,3,6,5,4,2]

参考

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

相关文章

网友评论

    本文标题:[Haskell] 拓扑排序

    本文链接:https://www.haomeiwen.com/subject/pklrottx.html