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 #ifdef REALLY_HASKELL_1_3
122 buildG bounds edges = accumArray (flip (:)) [] bounds edges
124 buildG bounds edges = accumArray (flip (:)) [] bounds [(,) k v | (k,v) <- edges]
127 transposeG :: Graph -> Graph
128 transposeG g = buildG (bounds g) (reverseE g)
130 reverseE :: Graph -> [Edge]
131 reverseE g = [ (w, v) | (v, w) <- edges g ]
133 outdegree :: Graph -> Table Int
134 outdegree = mapT numEdges
135 where numEdges v ws = length ws
137 indegree :: Graph -> Table Int
138 indegree = outdegree . transposeG
145 => [(node, key, [key])]
146 -> (Graph, Vertex -> (node, key, [key]))
148 = (graph, \v -> vertex_map ! v)
150 max_v = length edges - 1
151 bounds = (0,max_v) :: (Vertex, Vertex)
152 sorted_edges = sortLt lt edges
153 edges1 = zipWith (,) [0..] sorted_edges
155 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
156 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
157 vertex_map = array bounds edges1
159 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
161 -- key_vertex :: key -> Maybe Vertex
162 -- returns Nothing for non-interesting vertices
163 key_vertex k = find 0 max_v
167 find a b = case compare k (key_map ! mid) of
172 mid = (a + b) `div` 2
175 %************************************************************************
179 %************************************************************************
182 data Tree a = Node a (Forest a)
183 type Forest a = [Tree a]
185 mapTree :: (a -> b) -> (Tree a -> Tree b)
186 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
190 instance Show a => Show (Tree a) where
191 showsPrec p t s = showTree t ++ s
193 showTree :: Show a => Tree a -> String
194 showTree = drawTree . mapTree show
196 showForest :: Show a => Forest a -> String
197 showForest = unlines . map showTree
199 drawTree :: Tree String -> String
200 drawTree = unlines . draw
202 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
203 where this = s1 ++ x ++ " "
205 space n = take n (repeat ' ')
208 stLoop [t] = grp s2 " " (draw t)
209 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
211 rsLoop [t] = grp s5 " " (draw t)
212 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
214 grp fst rst = zipWith (++) (fst:repeat rst)
216 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
220 %************************************************************************
222 %* Depth first search
224 %************************************************************************
227 type Set s = STArray s Vertex Bool
229 mkEmpty :: Bounds -> ST s (Set s)
230 mkEmpty bnds = newSTArray bnds False
232 contains :: Set s -> Vertex -> ST s Bool
233 contains m v = readSTArray m v
235 include :: Set s -> Vertex -> ST s ()
236 include m v = writeSTArray m v True
240 dff :: Graph -> Forest Vertex
241 dff g = dfs g (vertices g)
243 dfs :: Graph -> [Vertex] -> Forest Vertex
244 dfs g vs = prune (bounds g) (map (generate g) vs)
246 generate :: Graph -> Vertex -> Tree Vertex
247 generate g v = Node v (map (generate g) (g!v))
249 prune :: Bounds -> Forest Vertex -> Forest Vertex
250 prune bnds ts = runST (mkEmpty bnds >>= \m ->
253 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
254 chop m [] = return []
255 chop m (Node v ts : us)
256 = contains m v >>= \visited ->
260 include m v >>= \_ ->
263 return (Node v as : bs)
267 %************************************************************************
271 %************************************************************************
273 ------------------------------------------------------------
274 -- Algorithm 1: depth first search numbering
275 ------------------------------------------------------------
278 --preorder :: Tree a -> [a]
279 preorder (Node a ts) = a : preorderF ts
281 preorderF :: Forest a -> [a]
282 preorderF ts = concat (map preorder ts)
284 preOrd :: Graph -> [Vertex]
285 preOrd = preorderF . dff
287 tabulate :: Bounds -> [Vertex] -> Table Int
288 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
290 preArr :: Bounds -> Forest Vertex -> Table Int
291 preArr bnds = tabulate bnds . preorderF
295 ------------------------------------------------------------
296 -- Algorithm 2: topological sorting
297 ------------------------------------------------------------
300 --postorder :: Tree a -> [a]
301 postorder (Node a ts) = postorderF ts ++ [a]
303 postorderF :: Forest a -> [a]
304 postorderF ts = concat (map postorder ts)
306 postOrd :: Graph -> [Vertex]
307 postOrd = postorderF . dff
309 topSort :: Graph -> [Vertex]
310 topSort = reverse . postOrd
314 ------------------------------------------------------------
315 -- Algorithm 3: connected components
316 ------------------------------------------------------------
319 components :: Graph -> Forest Vertex
320 components = dff . undirected
322 undirected :: Graph -> Graph
323 undirected g = buildG (bounds g) (edges g ++ reverseE g)
327 -- Algorithm 4: strongly connected components
330 scc :: Graph -> Forest Vertex
331 scc g = dfs g (reverse (postOrd (transposeG g)))
335 ------------------------------------------------------------
336 -- Algorithm 5: Classifying edges
337 ------------------------------------------------------------
340 tree :: Bounds -> Forest Vertex -> Graph
341 tree bnds ts = buildG bnds (concat (map flat ts))
343 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
346 back :: Graph -> Table Int -> Graph
347 back g post = mapT select g
348 where select v ws = [ w | w <- ws, post!v < post!w ]
350 cross :: Graph -> Table Int -> Table Int -> Graph
351 cross g pre post = mapT select g
352 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
354 forward :: Graph -> Graph -> Table Int -> Graph
355 forward g tree pre = mapT select g
356 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
360 ------------------------------------------------------------
361 -- Algorithm 6: Finding reachable vertices
362 ------------------------------------------------------------
365 reachable :: Graph -> Vertex -> [Vertex]
366 reachable g v = preorderF (dfs g [v])
368 path :: Graph -> Vertex -> Vertex -> Bool
369 path g v w = w `elem` (reachable g v)
373 ------------------------------------------------------------
374 -- Algorithm 7: Biconnected components
375 ------------------------------------------------------------
378 bcc :: Graph -> Forest [Vertex]
379 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
381 dnum = preArr (bounds g) forest
383 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
384 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
385 where us = map (do_label g dnum) ts
386 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
387 ++ [lu | Node (u,du,lu) xs <- us])
389 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
390 bicomps (Node (v,dv,lv) ts)
391 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
393 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
394 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
395 where collected = map collect ts
396 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
397 cs = concat [ if lw<dv then us else [Node (v:ws) us]
398 | (lw, Node ws us) <- collected ]