Cycle detection not working as expected