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 )
49 %************************************************************************
53 %************************************************************************
56 data SCC vertex = AcyclicSCC vertex
61 => [(node, key, [key])] -- The graph; its ok for the
62 -- out-list to contain keys which arent
63 -- a vertex key, they are ignored
66 stronglyConnComp edges
67 = map get_node (stronglyConnCompR edges)
69 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
70 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
72 -- The "R" interface is used when you expect to apply SCC to
73 -- the (some of) the result of SCC, so you dont want to lose the dependency info
76 => [(node, key, [key])] -- The graph; its ok for the
77 -- out-list to contain keys which arent
78 -- a vertex key, they are ignored
79 -> [SCC (node, key, [key])]
81 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
82 stronglyConnCompR edges
85 (graph, vertex_fn) = graphFromEdges edges
87 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
88 | otherwise = AcyclicSCC (vertex_fn v)
89 decode other = CyclicSCC (dec other [])
91 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
92 mentions_itself v = v `elem` (graph ! v)
95 %************************************************************************
99 %************************************************************************
104 type Table a = Array Vertex a
105 type Graph = Table [Vertex]
106 type Bounds = (Vertex, Vertex)
107 type Edge = (Vertex, Vertex)
111 vertices :: Graph -> [Vertex]
114 edges :: Graph -> [Edge]
115 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
117 mapT :: (Vertex -> a -> b) -> Table a -> Table b
118 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
120 buildG :: Bounds -> [Edge] -> Graph
121 buildG bounds edges = accumArray (flip (:)) [] bounds edges
123 transposeG :: Graph -> Graph
124 transposeG g = buildG (bounds g) (reverseE g)
126 reverseE :: Graph -> [Edge]
127 reverseE g = [ (w, v) | (v, w) <- edges g ]
129 outdegree :: Graph -> Table Int
130 outdegree = mapT numEdges
131 where numEdges v ws = length ws
133 indegree :: Graph -> Table Int
134 indegree = outdegree . transposeG
141 => [(node, key, [key])]
142 -> (Graph, Vertex -> (node, key, [key]))
144 = (graph, \v -> vertex_map ! v)
146 max_v = length edges - 1
147 bounds = (0,max_v) :: (Vertex, Vertex)
148 sorted_edges = sortLt lt edges
149 edges1 = zipWith (,) [0..] sorted_edges
151 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
152 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
153 vertex_map = array bounds edges1
155 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
157 -- key_vertex :: key -> Maybe Vertex
158 -- returns Nothing for non-interesting vertices
159 key_vertex k = find 0 max_v
163 find a b = case compare k (key_map ! mid) of
168 mid = (a + b) `div` 2
171 %************************************************************************
175 %************************************************************************
178 data Tree a = Node a (Forest a)
179 type Forest a = [Tree a]
181 mapTree :: (a -> b) -> (Tree a -> Tree b)
182 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
186 instance Show a => Show (Tree a) where
187 showsPrec p t s = showTree t ++ s
189 showTree :: Show a => Tree a -> String
190 showTree = drawTree . mapTree show
192 showForest :: Show a => Forest a -> String
193 showForest = unlines . map showTree
195 drawTree :: Tree String -> String
196 drawTree = unlines . draw
198 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
199 where this = s1 ++ x ++ " "
201 space n = take n (repeat ' ')
204 stLoop [t] = grp s2 " " (draw t)
205 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
207 rsLoop [t] = grp s5 " " (draw t)
208 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
210 grp fst rst = zipWith (++) (fst:repeat rst)
212 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
216 %************************************************************************
218 %* Depth first search
220 %************************************************************************
223 type Set s = STArray s Vertex Bool
225 mkEmpty :: Bounds -> ST s (Set s)
226 mkEmpty bnds = newSTArray bnds False
228 contains :: Set s -> Vertex -> ST s Bool
229 contains m v = readSTArray m v
231 include :: Set s -> Vertex -> ST s ()
232 include m v = writeSTArray m v True
236 dff :: Graph -> Forest Vertex
237 dff g = dfs g (vertices g)
239 dfs :: Graph -> [Vertex] -> Forest Vertex
240 dfs g vs = prune (bounds g) (map (generate g) vs)
242 generate :: Graph -> Vertex -> Tree Vertex
243 generate g v = Node v (map (generate g) (g!v))
245 prune :: Bounds -> Forest Vertex -> Forest Vertex
246 prune bnds ts = runST (mkEmpty bnds >>= \m ->
249 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
250 chop m [] = return []
251 chop m (Node v ts : us)
252 = contains m v >>= \visited ->
256 include m v >>= \_ ->
259 return (Node v as : bs)
263 %************************************************************************
267 %************************************************************************
269 ------------------------------------------------------------
270 -- Algorithm 1: depth first search numbering
271 ------------------------------------------------------------
274 --preorder :: Tree a -> [a]
275 preorder (Node a ts) = a : preorderF ts
277 preorderF :: Forest a -> [a]
278 preorderF ts = concat (map preorder ts)
280 preOrd :: Graph -> [Vertex]
281 preOrd = preorderF . dff
283 tabulate :: Bounds -> [Vertex] -> Table Int
284 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
286 preArr :: Bounds -> Forest Vertex -> Table Int
287 preArr bnds = tabulate bnds . preorderF
291 ------------------------------------------------------------
292 -- Algorithm 2: topological sorting
293 ------------------------------------------------------------
296 --postorder :: Tree a -> [a]
297 postorder (Node a ts) = postorderF ts ++ [a]
299 postorderF :: Forest a -> [a]
300 postorderF ts = concat (map postorder ts)
302 postOrd :: Graph -> [Vertex]
303 postOrd = postorderF . dff
305 topSort :: Graph -> [Vertex]
306 topSort = reverse . postOrd
310 ------------------------------------------------------------
311 -- Algorithm 3: connected components
312 ------------------------------------------------------------
315 components :: Graph -> Forest Vertex
316 components = dff . undirected
318 undirected :: Graph -> Graph
319 undirected g = buildG (bounds g) (edges g ++ reverseE g)
323 -- Algorithm 4: strongly connected components
326 scc :: Graph -> Forest Vertex
327 scc g = dfs g (reverse (postOrd (transposeG g)))
331 ------------------------------------------------------------
332 -- Algorithm 5: Classifying edges
333 ------------------------------------------------------------
336 tree :: Bounds -> Forest Vertex -> Graph
337 tree bnds ts = buildG bnds (concat (map flat ts))
339 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
342 back :: Graph -> Table Int -> Graph
343 back g post = mapT select g
344 where select v ws = [ w | w <- ws, post!v < post!w ]
346 cross :: Graph -> Table Int -> Table Int -> Graph
347 cross g pre post = mapT select g
348 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
350 forward :: Graph -> Graph -> Table Int -> Graph
351 forward g tree pre = mapT select g
352 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
356 ------------------------------------------------------------
357 -- Algorithm 6: Finding reachable vertices
358 ------------------------------------------------------------
361 reachable :: Graph -> Vertex -> [Vertex]
362 reachable g v = preorderF (dfs g [v])
364 path :: Graph -> Vertex -> Vertex -> Bool
365 path g v w = w `elem` (reachable g v)
369 ------------------------------------------------------------
370 -- Algorithm 7: Biconnected components
371 ------------------------------------------------------------
374 bcc :: Graph -> Forest [Vertex]
375 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
377 dnum = preArr (bounds g) forest
379 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
380 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
381 where us = map (do_label g dnum) ts
382 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
383 ++ [lu | Node (u,du,lu) xs <- us])
385 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
386 bicomps (Node (v,dv,lv) ts)
387 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
389 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
390 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
391 where collected = map collect ts
392 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
393 cs = concat [ if lw<dv then us else [Node (v:ws) us]
394 | (lw, Node ws us) <- collected ]