add algorithm to detect the loop