Added function to detect cycles