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] = [u, v] denotes a bidirectional edge connecting nodes u and v.
The distance between two nodes a and b is the minimum number of edges needed to go from a to b.
Return an integer array answer of size n, where answer[i] is the minimum distance between node i and any node in the cycle.
Function Signature
def distance_to_cycle(n: int, edges: list[list[int]]) -> list[int]:
Rules
-
Each pair in
edges
is one undirected edge. Edges are listed once each, in any order.
-
A node on the cycle has distance
0
.
-
answer[i]
is the value for node
i
, so the output is in node order.
Constraints
-
3 <= n <= 10^5
-
edges.length == n
-
edges[i].length == 2
-
0 <= u, v <= n - 1
-
u != v
-
The graph is connected.
-
The graph has exactly one cycle.
-
There is at most one edge between any pair of nodes.
Examples
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]
The cycle is 1, 2, 4, 3 and back to 1, so those four nodes have distance 0. Node 0 hangs off cycle node 1 and node 5 hangs off cycle node 2, so both are 1 away, and node 6 hangs off node 5, so it is 2 away.
Input: n = 9, edges = [[0,1],[1,2],[0,2],[2,6],[6,7],[6,8],[1,3],[3,4],[3,5]]
Output: [0,0,0,1,2,2,1,2,2]
The cycle is the triangle 0, 1, 2. Node 3 attaches to cycle node 1 and node 6 attaches to cycle node 2, so both are 1 away, and their children 4, 5, 7 and 8 are 2 away.