So I've successfully implemented a recursive tarjan's that provides me the SCC of a graph
My recursive implementation is as follows:
public void DFSRecursive(long currentNode){
low[currentNode] = preCount++;
visited[currentNode] = true;
stack.Push(currentNode);
long minimum = low[currentNode];
foreach(long successorNode in SuccessorMap[currentNode])
{
if(!visited[successorNode])
{
DFSRecursive(successorNode);
}
if(low[successorNode] < minimum)
{
minimum = low[successorNode];
}
}
if(minimum < low[currentNode])
{
low[currentNode] = minimum;
return;
}
List<long> component = new List<long>();
long stackTop;
do
{
stackTop = stack.Pop();
component.Add(stackTop);
}
while(stackTop != currentNode);
SCComponent.Add(component);
}
Now I need to convert this to an iterative solution. I have already checked a lot of resources to help me out including a very similar SO question (Non-recursive version of Tarjan's algorithm). I can't use an enumerator since I have to deal with long values and the successor indices of the current state have been stored in a Dictionary(SuccessorMap[]) (need to deal with graphs with # of Nodes > 5 billion).
I have followed the general guidelines available to convert a recursive solution to an iterative one:
- Replaced the recursive call with push to the local stack
- Replaced "returns" with pop from local stack
Set the variables at the start of the loop and popped from the local stack
public void DFSIterative(long currentNode) { var internalStack = new Stack<long>(); low[currentNode] = preCount++; stack.Push(currentNode); long minimum = low[currentNode]; internalStack.Push(currentNode); while(!(internalStack.Count == 0)) { currentNode = internalStack.Pop(); visited[currentNode] = true; foreach(long successorNode in SuccessorMap[currentNode]) { if(!visited[successorNode]) { internalStack.Push(successorNode); } if(low[successorNode] < minimum) { minimum = low[successorNode]; } } if(minimum < low[currentNode]) { low[currentNode] = minimum; return; } } List<long> component = new List<long>(); long stackTop; do { stackTop = stack.Pop(); component.Add(w); } while(stackTop != currentNode); SCComponent.Add(component); }
I recognize that the do-while loop in the iterative method will always throw a InvalidOperationException(stack empty)
, but i haven't been figure out implement the recursive do-while iteratively.
Would really appreciate any sort of help to assist me.