added solution for cycle detection