Added cycle detection function: has_cycles