Fixed infinite loops while detecting cycles.