Distance to a Cycle in Undirected Graph Problem
Description
LeetCode Problem 2204.
You are given a positive integer n representing the number of nodes in a connected undirected graph containing exactly one cycle. The nodes are numbered from 0 to n - 1 (inclusive).
You are also given a 2D integer array edges, where edges[i] = [node1_i, node2_i] denotes that there is a bidirectional edge connecting node1_i and node2_i in the graph.
The distance between two nodes a and b is defined to be the minimum number of edges that are needed to go from a to b.
Return an integer array answer of size n, where answer[i] is the minimum distance between the i^th node and any node in the cycle.
Example 1:

Input: n = 7, edges = [[1,2],[2,4],[4,3],[3,1],[0,1],[5,2],[6,5]]
Output: [1,0,0,0,0,1,2]
Explanation:
The nodes 1, 2, 3, and 4 form the cycle.
The distance from 0 to 1 is 1.
The distance from 1 to 1 is 0.
The distance from 2 to 2 is 0.
The distance from 3 to 3 is 0.
The distance from 4 to 4 is 0.
The distance from 5 to 2 is 1.
The distance from 6 to 2 is 2.
Example 2:

Input: n = 9, edges = [[0,1],[1,2],[0,2],[2,6],[6,7],[6,8],[0,3],[3,4],[3,5]]
Output: [0,0,0,1,2,2,1,2,2]
Explanation:
The nodes 0, 1, and 2 form the cycle.
The distance from 0 to 0 is 0.
The distance from 1 to 1 is 0.
The distance from 2 to 2 is 0.
The distance from 3 to 1 is 1.
The distance from 4 to 1 is 2.
The distance from 5 to 1 is 2.
The distance from 6 to 2 is 1.
The distance from 7 to 2 is 2.
The distance from 8 to 2 is 2.
Constraints:
3 <= n <= 10^5edges.length == nedges[i].length == 20 <= node1_i, node2_i <= n - 1node1_i != node2_i- The graph is connected.
- The graph has exactly one cycle.
- There is at most one edge between any pair of vertices.
Solution
Approach: Topological sorting
Build the adjacency sets g from edges. The graph has exactly one cycle, so peeling off degree-1 nodes layer by layer from the outside leaves exactly the cycle.
Start a queue with every node of degree 1. Pop a node, record it in seq (the order of removal), remember in f[i] its one remaining neighbour (the one closer to the cycle), delete it from that neighbour's set, and if the neighbour now has degree 1, push it.
Nodes on the cycle keep distance 0. Then walk seq backwards: when node i is processed, f[i] already has its final distance, so ans[i] = ans[f[i]] + 1.
Complexity: O(n) time, O(n) space.
from collections import defaultdict, deque
class Solution:
def distanceToCycle(self, n: int, edges: List[List[int]]) -> List[int]:
g = defaultdict(set)
for a, b in edges:
g[a].add(b)
g[b].add(a)
q = deque(i for i in range(n) if len(g[i]) == 1)
f = [0] * n
seq = []
while q:
i = q.popleft()
seq.append(i)
for j in g[i]:
g[j].remove(i)
f[i] = j
if len(g[j]) == 1:
q.append(j)
g[i].clear()
ans = [0] * n
for i in seq[::-1]:
ans[i] = ans[f[i]] + 1
return ans