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)
42 import Util ( sortLt )
46 %************************************************************************
50 %************************************************************************
53 data SCC vertex = AcyclicSCC vertex
58 => [(node, key, [key])] -- The graph; its ok for the
59 -- out-list to contain keys which arent
60 -- a vertex key, they are ignored
63 stronglyConnComp edges
64 = map get_node (stronglyConnCompR edges)
66 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
67 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
69 -- The "R" interface is used when you expect to apply SCC to
70 -- the (some of) the result of SCC, so you dont want to lose the dependency info
73 => [(node, key, [key])] -- The graph; its ok for the
74 -- out-list to contain keys which arent
75 -- a vertex key, they are ignored
76 -> [SCC (node, key, [key])]
78 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
79 stronglyConnCompR edges
82 (graph, vertex_fn) = graphFromEdges edges
84 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
85 | otherwise = AcyclicSCC (vertex_fn v)
86 decode other = CyclicSCC (dec other [])
88 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
89 mentions_itself v = v `elem` (graph ! v)
92 %************************************************************************
96 %************************************************************************
101 type Table a = Array Vertex a
102 type Graph = Table [Vertex]
103 type Bounds = (Vertex, Vertex)
104 type Edge = (Vertex, Vertex)
108 vertices :: Graph -> [Vertex]
111 edges :: Graph -> [Edge]
112 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
114 mapT :: (Vertex -> a -> b) -> Table a -> Table b
115 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
117 buildG :: Bounds -> [Edge] -> Graph
118 #ifdef REALLY_HASKELL_1_3
119 buildG bounds edges = accumArray (flip (:)) [] bounds edges
121 buildG bounds edges = accumArray (flip (:)) [] bounds [(,) k v | (k,v) <- edges]
124 transposeG :: Graph -> Graph
125 transposeG g = buildG (bounds g) (reverseE g)
127 reverseE :: Graph -> [Edge]
128 reverseE g = [ (w, v) | (v, w) <- edges g ]
130 outdegree :: Graph -> Table Int
131 outdegree = mapT numEdges
132 where numEdges v ws = length ws
134 indegree :: Graph -> Table Int
135 indegree = outdegree . transposeG
142 => [(node, key, [key])]
143 -> (Graph, Vertex -> (node, key, [key]))
145 = (graph, \v -> vertex_map ! v)
147 max_v = length edges - 1
148 bounds = (0,max_v) :: (Vertex, Vertex)
149 sorted_edges = sortLt lt edges
150 edges1 = zipWith (,) [0..] sorted_edges
152 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
153 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
154 vertex_map = array bounds edges1
156 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
158 -- key_vertex :: key -> Maybe Vertex
159 -- returns Nothing for non-interesting vertices
160 key_vertex k = find 0 max_v
164 find a b = case compare k (key_map ! mid) of
169 mid = (a + b) `div` 2
172 %************************************************************************
176 %************************************************************************
179 data Tree a = Node a (Forest a)
180 type Forest a = [Tree a]
182 mapTree :: (a -> b) -> (Tree a -> Tree b)
183 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
187 instance Show a => Show (Tree a) where
188 showsPrec p t s = showTree t ++ s
190 showTree :: Show a => Tree a -> String
191 showTree = drawTree . mapTree show
193 showForest :: Show a => Forest a -> String
194 showForest = unlines . map showTree
196 drawTree :: Tree String -> String
197 drawTree = unlines . draw
199 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
200 where this = s1 ++ x ++ " "
202 space n = take n (repeat ' ')
205 stLoop [t] = grp s2 " " (draw t)
206 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
208 rsLoop [t] = grp s5 " " (draw t)
209 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
211 grp fst rst = zipWith (++) (fst:repeat rst)
213 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
217 %************************************************************************
219 %* Depth first search
221 %************************************************************************
224 type Set s = MutableArray s Vertex Bool
226 mkEmpty :: Bounds -> ST s (Set s)
227 mkEmpty bnds = newArray bnds False
229 contains :: Set s -> Vertex -> ST s Bool
230 contains m v = readArray m v
232 include :: Set s -> Vertex -> ST s ()
233 include m v = writeArray m v True
237 dff :: Graph -> Forest Vertex
238 dff g = dfs g (vertices g)
240 dfs :: Graph -> [Vertex] -> Forest Vertex
241 dfs g vs = prune (bounds g) (map (generate g) vs)
243 generate :: Graph -> Vertex -> Tree Vertex
244 generate g v = Node v (map (generate g) (g!v))
246 prune :: Bounds -> Forest Vertex -> Forest Vertex
247 prune bnds ts = runST (mkEmpty bnds >>= \m ->
250 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
251 chop m [] = return []
252 chop m (Node v ts : us)
253 = contains m v >>= \visited ->
257 include m v >>= \_ ->
260 return (Node v as : bs)
264 %************************************************************************
268 %************************************************************************
270 ------------------------------------------------------------
271 -- Algorithm 1: depth first search numbering
272 ------------------------------------------------------------
275 --preorder :: Tree a -> [a]
276 preorder (Node a ts) = a : preorderF ts
278 preorderF :: Forest a -> [a]
279 preorderF ts = concat (map preorder ts)
281 preOrd :: Graph -> [Vertex]
282 preOrd = preorderF . dff
284 tabulate :: Bounds -> [Vertex] -> Table Int
285 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
287 preArr :: Bounds -> Forest Vertex -> Table Int
288 preArr bnds = tabulate bnds . preorderF
292 ------------------------------------------------------------
293 -- Algorithm 2: topological sorting
294 ------------------------------------------------------------
297 --postorder :: Tree a -> [a]
298 postorder (Node a ts) = postorderF ts ++ [a]
300 postorderF :: Forest a -> [a]
301 postorderF ts = concat (map postorder ts)
303 postOrd :: Graph -> [Vertex]
304 postOrd = postorderF . dff
306 topSort :: Graph -> [Vertex]
307 topSort = reverse . postOrd
311 ------------------------------------------------------------
312 -- Algorithm 3: connected components
313 ------------------------------------------------------------
316 components :: Graph -> Forest Vertex
317 components = dff . undirected
319 undirected :: Graph -> Graph
320 undirected g = buildG (bounds g) (edges g ++ reverseE g)
324 -- Algorithm 4: strongly connected components
327 scc :: Graph -> Forest Vertex
328 scc g = dfs g (reverse (postOrd (transposeG g)))
332 ------------------------------------------------------------
333 -- Algorithm 5: Classifying edges
334 ------------------------------------------------------------
337 tree :: Bounds -> Forest Vertex -> Graph
338 tree bnds ts = buildG bnds (concat (map flat ts))
340 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
343 back :: Graph -> Table Int -> Graph
344 back g post = mapT select g
345 where select v ws = [ w | w <- ws, post!v < post!w ]
347 cross :: Graph -> Table Int -> Table Int -> Graph
348 cross g pre post = mapT select g
349 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
351 forward :: Graph -> Graph -> Table Int -> Graph
352 forward g tree pre = mapT select g
353 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
357 ------------------------------------------------------------
358 -- Algorithm 6: Finding reachable vertices
359 ------------------------------------------------------------
362 reachable :: Graph -> Vertex -> [Vertex]
363 reachable g v = preorderF (dfs g [v])
365 path :: Graph -> Vertex -> Vertex -> Bool
366 path g v w = w `elem` (reachable g v)
370 ------------------------------------------------------------
371 -- Algorithm 7: Biconnected components
372 ------------------------------------------------------------
375 bcc :: Graph -> Forest [Vertex]
376 bcc g = (concat . map bicomps . map (label g dnum)) forest
378 dnum = preArr (bounds g) forest
380 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
381 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
382 where us = map (label g dnum) ts
383 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
384 ++ [lu | Node (u,du,lu) xs <- us])
386 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
387 bicomps (Node (v,dv,lv) ts)
388 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
390 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
391 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
392 where collected = map collect ts
393 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
394 cs = concat [ if lw<dv then us else [Node (v:ws) us]
395 | (lw, Node ws us) <- collected ]