| 1 |
(* |
| 2 |
* Tarjan's algorithm |
| 3 |
* |
| 4 |
* This module computes strongly connected components (SCC) of |
| 5 |
* a graph. Each SCC is represented as a list of nodes. All nodes |
| 6 |
* are folded together with a user supplied function. |
| 7 |
* |
| 8 |
* -- Allen |
| 9 |
*) |
| 10 |
|
| 11 |
structure GraphSCC : GRAPH_STRONGLY_CONNECTED_COMPONENTS = |
| 12 |
struct |
| 13 |
|
| 14 |
structure G = Graph |
| 15 |
structure A = Array |
| 16 |
|
| 17 |
fun scc' {N, nodes, out_edges} process S = |
| 18 |
let val onstack = Word8Array.array(N,0w0) |
| 19 |
val dfsnum = A.array(N,~1) |
| 20 |
fun dfs(v,num,stack,S) = |
| 21 |
let val dfsnum_v = num |
| 22 |
fun f([],num,stack,low_v,S) = (num,stack,low_v,S) |
| 23 |
| f((_,w,_)::es,num,stack,low_v,S) = |
| 24 |
let val dfsnum_w = A.sub(dfsnum,w) |
| 25 |
in if dfsnum_w = ~1 then |
| 26 |
let val (num,stack,dfsnum_w,low_w,S) = dfs(w,num,stack,S) |
| 27 |
in f(es,num,stack,Int.min(low_v,low_w),S) end |
| 28 |
else |
| 29 |
if dfsnum_w < dfsnum_v andalso |
| 30 |
Word8Array.sub(onstack,w) = 0w1 |
| 31 |
then f(es,num,stack,Int.min(dfsnum_w,low_v),S) |
| 32 |
else |
| 33 |
f(es,num,stack,low_v,S) |
| 34 |
end |
| 35 |
val _ = A.update(dfsnum,v,dfsnum_v) |
| 36 |
val _ = Word8Array.update(onstack,v,0w1) |
| 37 |
val (num,stack,low_v,S) = |
| 38 |
f(out_edges v,num+1,v::stack,dfsnum_v,S) |
| 39 |
fun pop([],SCC,S) = ([],S) |
| 40 |
| pop(x::stack,SCC,S) = |
| 41 |
let val SCC = x::SCC |
| 42 |
val _ = Word8Array.update(onstack,x,0w0) |
| 43 |
in if x = v then (stack,process(SCC,S)) |
| 44 |
else pop(stack,SCC,S) |
| 45 |
end |
| 46 |
val (stack,S) = if low_v = dfsnum_v then pop(stack,[],S) |
| 47 |
else (stack,S) |
| 48 |
in (num,stack,dfsnum_v,low_v,S) |
| 49 |
end |
| 50 |
fun dfsAll([],S) = S |
| 51 |
| dfsAll(n::nodes,S) = |
| 52 |
if A.sub(dfsnum,n) = ~1 then |
| 53 |
let val (_,_,_,_,S) = dfs(n,0,[],S) |
| 54 |
in dfsAll(nodes,S) end |
| 55 |
else dfsAll(nodes,S) |
| 56 |
in dfsAll(nodes,S) |
| 57 |
end |
| 58 |
|
| 59 |
fun scc (G.GRAPH G) = |
| 60 |
scc' {N = #capacity G (), nodes= map #1 (#nodes G ()), |
| 61 |
out_edges= #out_edges G} |
| 62 |
|
| 63 |
end |
| 64 |
|