1347. Distance to a Cycle in Undirected Graph

Hard
Depth-First Search
Breadth-First Search
Union Find
Graph

Description

Hints

Hint 1
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle.
Hint 2
How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the node that was seen twice and all the nodes that we visited in between.
Hint 3
Now that we know which nodes are part of the cycle, how can we find the distances? We can run a multi-source BFS starting from the nodes in the cycle and expanding outward.

Statistics

Acceptance
73.2%
Submissions
9,066
Accepted
6,634