You are given a positive integer n
representing n
nodes in a connected undirected graph, where the nodes are numbered from 0
to n - 1
.
You are also given an array edges
, where edges[i] = [ui, vi]
denotes that there is an edge between nodes ui
and vi
in the graph.
The distance from a node v
to a cycle is the minimum number of edges needed to reach a node in a cycle from node v
. If node v
is part of a cycle, its distance is 0
.
Return an array answer
of length n
, where answer[i]
is the distance from node i
to a cycle.
Example 1:
Input: n = 9, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6],[6,1],[2,7],[7,8]] Output: [1,0,0,0,1,2,1,1,2]
Example 2:
Input: n = 7, edges = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,6]] Output: [0,0,0,1,2,3,4]
Constraints:
3 <= n <= 105
n <= edges.length <= 2 * n
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi