Graph Theory37 sections · 1633 units
Open in Course

CSES 1197 Cycle Finding - Lessons

(summary)

Parent pointers let you reconstruct paths and cycles, not distances. Always track parents when you need to output the actual path or cycle. Walking back nn steps guarantees you land inside the cycle, even if the improved node is outside. This is because any path with nn edges in a graph with nn nodes must repeat a node.

This double-walk technique works because the parent tree contains the cycle. The first nn steps ensure you enter the cycle, and the second loop extracts it.