extract common implementation of Tarjan's algorithm