You may apply Floyd-Warshall algorithm to this problem.
Floyd-Warshall algorithm can be used for both numbering paths and marking infinite loops. Here is a reference solution.