refactoring checkPathLoop