We can use Floyd’s cycle detection algorithm to solve this problem.
A good example that slowed how to make your code modular.
No summary
This post explained each step of the solution.
No summary
Drew some comments to visualize each step of the solution.
Solving this problem with classic fast and slow pointers solution
No summary
A problem set of Paint House problems.
A problem set of Depth of Binary Tree problems.