Tarjan's algorithm for cycle detection.