Debian Codegraph @

lib/mlrisc-lib/MLRISC/graphs/graph-dfs.sml

raw
1 (*
2 * Some simple functions for performing depth first search
3 *
4 * -- Allen
5 *)
6 structure GraphDFS : GRAPH_DEPTH_FIRST_SEARCH =
7 struct
8
9 structure G = Graph
10 structure A = Array
11 structure S = BitSet
12
13 (*
14 * Depth first search
15 *)
16 fun dfs (G.GRAPH G) f g roots =
17 let val visited = S.create(#capacity G ())
18 fun traverse n =
19 if S.markAndTest(visited,n) then ()
20 else (f n; app traverse_edge (#out_edges G n))
21 and traverse_edge (e as (_,n,_)) =
22 if S.markAndTest(visited,n) then ()
23 else (g e; f n; app traverse_edge (#out_edges G n))
24 in app traverse roots end
25
26 (*
27 * Depth first search fold
28 *)
29 fun dfsfold (G.GRAPH G) f g roots (x,y) =
30 let val visited = S.create(#capacity G ())
31 fun traverse(n,x,y) =
32 if S.markAndTest(visited,n) then (x,y)
33 else traverse_edges(#out_edges G n,f(n,x),y)
34 and traverse_edges ([],x,y) = (x,y)
35 | traverse_edges ((e as (_,n,_))::es,x,y) =
36 if S.markAndTest(visited,n) then traverse_edges(es,x,y)
37 else let val y = g(e,y)
38 val x = f(n,x)
39 val (x,y) = traverse_edges(#out_edges G n,x,y)
40 in traverse_edges(es,x,y) end
41 and traverseAll([],x,y) = (x,y)
42 | traverseAll(n::ns,x,y) =
43 let val (x,y) = traverse(n,x,y)
44 in traverseAll(ns,x,y) end
45 in traverseAll(roots,x,y) end
46
47
48 fun dfsnum (G.GRAPH G) roots =
49 let val N = #capacity G ()
50 val dfsnum = A.array(N,~1)
51 val compnum = A.array(N,~1)
52 fun traverse([],d,c) = c
53 | traverse(n::ns,d,c) =
54 if A.sub(dfsnum,n) >= 0 then traverse(ns,d,c)
55 else let val _ = A.update(dfsnum,n,d);
56 val c = traverse(#succ G n,d+1,c)
57 in A.update(compnum,n,c);
58 traverse(ns,d,c+1)
59 end
60 in traverse(roots,0,0); {dfsnum=dfsnum,compnum=compnum} end
61
62 fun preorder_numbering (G.GRAPH G) root =
63 let val N = #capacity G ()
64 val P = A.array(N,~1)
65 fun f(i,n) =
66 if A.sub(P,i) = ~1 then
67 let fun g([],n) = n
68 | g((_,j,_)::es,n) = g(es,f(j,n))
69 in A.update(P,i,n); g(#out_edges G i,n+1) end
70 else n
71 in f(root,0); P end
72
73 fun postorder_numbering (G.GRAPH G) root =
74 let val N = #capacity G ()
75 val P = A.array(N,~2)
76 fun f (i,n) =
77 if A.sub(P,i) = ~2 then
78 let fun g([],n) = n
79 | g((_,j,_)::es,n) = g(es,f(j,n))
80 val _ = A.update(P,i,~1)
81 val n = g(#out_edges G i,n)
82 in A.update(P,i,n); n+1
83 end
84 else n
85 in f(root,0); P end
86 end
87