Recently I have been researching a matching algorithm for a certain sector of a swap market. This turned into a graph problem requiring finding strongly connected components of the graph (and then cycles) to generate possible multi-broker trades. I turned to Wikipedia for help and found this nice Tarjan’s algorithm:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
algorithm tarjan is | |
input: graph G = (V, E) | |
output: set of strongly connected components (sets of vertices) | |
index := 0 | |
S := empty | |
for each v in V do | |
if (v.index is undefined) then | |
strongconnect(v) | |
end if | |
repeat | |
function strongconnect(v) | |
// Set the depth index for v to the smallest unused index | |
v.index := index | |
v.lowlink := index | |
index := index + 1 | |
S.push(v) | |
// Consider successors of v | |
for each (v, w) in E do | |
if (w.index is undefined) then | |
// Successor w has not yet been visited; recurse on it | |
strongconnect(w) | |
v.lowlink := min(v.lowlink, w.lowlink) | |
else if (w is in S) then | |
// Successor w is in stack S and hence in the current SCC | |
v.lowlink := min(v.lowlink, w.index) | |
end if | |
repeat | |
// If v is a root node, pop the stack and generate an SCC | |
if (v.lowlink = v.index) then | |
start a new strongly connected component | |
repeat | |
w := S.pop() | |
add w to current strongly connected component | |
until (w = v) | |
output the current strongly connected component | |
end if | |
end function |
I quickly coded it up as-is in Scala, my language of choice currently. All worked fine, but it did not feel right in Scala, relying so heavily on mutable state. It took me a bit but I managed to rework the algorithm into a purely functional style. Here is the code: