4 -- At present the only one with a "nice" external interface
5 stronglyConnComp, stronglyConnCompR, SCC(..),
8 graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
23 # include "HsVersions.h"
25 ------------------------------------------------------------------------------
26 -- A version of the graph algorithms described in:
28 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
29 -- by David King and John Launchbury
31 -- Also included is some additional code for printing tree structures ...
32 ------------------------------------------------------------------------------
35 #define ARR_ELT (COMMA)
37 import Util ( sortLt )
50 %************************************************************************
54 %************************************************************************
57 data SCC vertex = AcyclicSCC vertex
62 => [(node, key, [key])] -- The graph; its ok for the
63 -- out-list to contain keys which arent
64 -- a vertex key, they are ignored
67 stronglyConnComp edges
68 = map get_node (stronglyConnCompR edges)
70 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
71 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
73 -- The "R" interface is used when you expect to apply SCC to
74 -- the (some of) the result of SCC, so you dont want to lose the dependency info
77 => [(node, key, [key])] -- The graph; its ok for the
78 -- out-list to contain keys which arent
79 -- a vertex key, they are ignored
80 -> [SCC (node, key, [key])]
82 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
83 stronglyConnCompR edges
86 (graph, vertex_fn) = graphFromEdges edges
88 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
89 | otherwise = AcyclicSCC (vertex_fn v)
90 decode other = CyclicSCC (dec other [])
92 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
93 mentions_itself v = v `elem` (graph ! v)
96 %************************************************************************
100 %************************************************************************
105 type Table a = Array Vertex a
106 type Graph = Table [Vertex]
107 type Bounds = (Vertex, Vertex)
108 type Edge = (Vertex, Vertex)
112 vertices :: Graph -> [Vertex]
115 edges :: Graph -> [Edge]
116 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
118 mapT :: (Vertex -> a -> b) -> Table a -> Table b
119 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
121 buildG :: Bounds -> [Edge] -> Graph
122 #ifdef REALLY_HASKELL_1_3
123 buildG bounds edges = accumArray (flip (:)) [] bounds edges
125 buildG bounds edges = accumArray (flip (:)) [] bounds [(,) k v | (k,v) <- edges]
128 transposeG :: Graph -> Graph
129 transposeG g = buildG (bounds g) (reverseE g)
131 reverseE :: Graph -> [Edge]
132 reverseE g = [ (w, v) | (v, w) <- edges g ]
134 outdegree :: Graph -> Table Int
135 outdegree = mapT numEdges
136 where numEdges v ws = length ws
138 indegree :: Graph -> Table Int
139 indegree = outdegree . transposeG
146 => [(node, key, [key])]
147 -> (Graph, Vertex -> (node, key, [key]))
149 = (graph, \v -> vertex_map ! v)
151 max_v = length edges - 1
152 bounds = (0,max_v) :: (Vertex, Vertex)
153 sorted_edges = sortLt lt edges
154 edges1 = zipWith (,) [0..] sorted_edges
156 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
157 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
158 vertex_map = array bounds edges1
160 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
162 -- key_vertex :: key -> Maybe Vertex
163 -- returns Nothing for non-interesting vertices
164 key_vertex k = find 0 max_v
168 find a b = case compare k (key_map ! mid) of
173 mid = (a + b) `div` 2
176 %************************************************************************
180 %************************************************************************
183 data Tree a = Node a (Forest a)
184 type Forest a = [Tree a]
186 mapTree :: (a -> b) -> (Tree a -> Tree b)
187 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
191 instance Show a => Show (Tree a) where
192 showsPrec p t s = showTree t ++ s
194 showTree :: Show a => Tree a -> String
195 showTree = drawTree . mapTree show
197 showForest :: Show a => Forest a -> String
198 showForest = unlines . map showTree
200 drawTree :: Tree String -> String
201 drawTree = unlines . draw
203 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
204 where this = s1 ++ x ++ " "
206 space n = take n (repeat ' ')
209 stLoop [t] = grp s2 " " (draw t)
210 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
212 rsLoop [t] = grp s5 " " (draw t)
213 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
215 grp fst rst = zipWith (++) (fst:repeat rst)
217 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
221 %************************************************************************
223 %* Depth first search
225 %************************************************************************
228 type Set s = MutableArray s Vertex Bool
230 mkEmpty :: Bounds -> ST s (Set s)
231 mkEmpty bnds = newArray bnds False
233 contains :: Set s -> Vertex -> ST s Bool
234 contains m v = readArray m v
236 include :: Set s -> Vertex -> ST s ()
237 include m v = writeArray m v True
241 dff :: Graph -> Forest Vertex
242 dff g = dfs g (vertices g)
244 dfs :: Graph -> [Vertex] -> Forest Vertex
245 dfs g vs = prune (bounds g) (map (generate g) vs)
247 generate :: Graph -> Vertex -> Tree Vertex
248 generate g v = Node v (map (generate g) (g!v))
250 prune :: Bounds -> Forest Vertex -> Forest Vertex
251 prune bnds ts = runST (mkEmpty bnds >>= \m ->
254 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
255 chop m [] = return []
256 chop m (Node v ts : us)
257 = contains m v >>= \visited ->
261 include m v >>= \_ ->
264 return (Node v as : bs)
268 %************************************************************************
272 %************************************************************************
274 ------------------------------------------------------------
275 -- Algorithm 1: depth first search numbering
276 ------------------------------------------------------------
279 --preorder :: Tree a -> [a]
280 preorder (Node a ts) = a : preorderF ts
282 preorderF :: Forest a -> [a]
283 preorderF ts = concat (map preorder ts)
285 preOrd :: Graph -> [Vertex]
286 preOrd = preorderF . dff
288 tabulate :: Bounds -> [Vertex] -> Table Int
289 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
291 preArr :: Bounds -> Forest Vertex -> Table Int
292 preArr bnds = tabulate bnds . preorderF
296 ------------------------------------------------------------
297 -- Algorithm 2: topological sorting
298 ------------------------------------------------------------
301 --postorder :: Tree a -> [a]
302 postorder (Node a ts) = postorderF ts ++ [a]
304 postorderF :: Forest a -> [a]
305 postorderF ts = concat (map postorder ts)
307 postOrd :: Graph -> [Vertex]
308 postOrd = postorderF . dff
310 topSort :: Graph -> [Vertex]
311 topSort = reverse . postOrd
315 ------------------------------------------------------------
316 -- Algorithm 3: connected components
317 ------------------------------------------------------------
320 components :: Graph -> Forest Vertex
321 components = dff . undirected
323 undirected :: Graph -> Graph
324 undirected g = buildG (bounds g) (edges g ++ reverseE g)
328 -- Algorithm 4: strongly connected components
331 scc :: Graph -> Forest Vertex
332 scc g = dfs g (reverse (postOrd (transposeG g)))
336 ------------------------------------------------------------
337 -- Algorithm 5: Classifying edges
338 ------------------------------------------------------------
341 tree :: Bounds -> Forest Vertex -> Graph
342 tree bnds ts = buildG bnds (concat (map flat ts))
344 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
347 back :: Graph -> Table Int -> Graph
348 back g post = mapT select g
349 where select v ws = [ w | w <- ws, post!v < post!w ]
351 cross :: Graph -> Table Int -> Table Int -> Graph
352 cross g pre post = mapT select g
353 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
355 forward :: Graph -> Graph -> Table Int -> Graph
356 forward g tree pre = mapT select g
357 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
361 ------------------------------------------------------------
362 -- Algorithm 6: Finding reachable vertices
363 ------------------------------------------------------------
366 reachable :: Graph -> Vertex -> [Vertex]
367 reachable g v = preorderF (dfs g [v])
369 path :: Graph -> Vertex -> Vertex -> Bool
370 path g v w = w `elem` (reachable g v)
374 ------------------------------------------------------------
375 -- Algorithm 7: Biconnected components
376 ------------------------------------------------------------
379 bcc :: Graph -> Forest [Vertex]
380 bcc g = (concat . map bicomps . map (label g dnum)) forest
382 dnum = preArr (bounds g) forest
384 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
385 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
386 where us = map (label g dnum) ts
387 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
388 ++ [lu | Node (u,du,lu) xs <- us])
390 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
391 bicomps (Node (v,dv,lv) ts)
392 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
394 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
395 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
396 where collected = map collect ts
397 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
398 cs = concat [ if lw<dv then us else [Node (v:ws) us]
399 | (lw, Node ws us) <- collected ]