
The graph is connected.
There is, at most, one edge between any pair of nodes.
There is exactly one cycle in the graph.
Input: N=7, edges=[[1, 2], [2, 3], [3, 4], [4, 1], [0, 1], [5, 2], [6, 5]]
Output: [1, 0, 0, 0, 0, 1, 2]
Explanation: The Nodes 1, 2, 3, and 4 form a cycle.
The distance between nodes 0 to 1 is 1.
The distance between nodes 1 to 1 is 0.
The distance between nodes 2 to 2 is 0.
The distance between nodes 3 to 3 is 0.
The distance between nodes 4 to 4 is 0.
The distance between nodes 5 to 2 is 1.
The distance between nodes 6 to 2 is 2.
First-line contains 'T', denoting the number of Test cases.
For each Test case:
The first line contains a single integer, ‘N,’ denoting the number of nodes in the graph.
The next ‘N’ lines contain two integers, ‘node0’ and ‘node1’, denoting an undirected edge between ‘node0’ and ‘node1’.
Return the array ‘ANSWER’.
You don't need to print anything. Just implement the given function.
1 <= 'T' <= 10
3 <= 'N' <= 10^5
0 <= ‘node0’, ‘node1’ <=’N’-1
‘node0’ != ’node1’
Time Limit: 1 sec
This problem can be solved in two steps. The first step is detecting a cycle, and the second is finding the distance for each node.
For the detecting cycle, we can remove leaf nodes and the associated edges. Any node with only one edge is known as a leaf node. All nodes left are part of the cycle.
For step two, push all the remaining nodes in a queue and start bfs to calculate the distance for all nodes.
The steps are as follows:-