


Any pair of cities (x, y) have at most one road connecting them directly.
A city ‘x’ is reachable by any other city ‘y’ via some group of roads.
In input data, cities are numbered from [0, 1, ……. N-1].
The first line contains ‘T’, denoting the number of tests.
For each Test :
The first line contains two integers, ‘N’ and ‘M’, denoting the number of cities and roads, respectively.
Next ‘M’ lines contain two integers (x[i], y[i]), denoting a bi-directional road between city ‘x[i]’ and city ‘y[i]’.
For each test, print an integer, denoting the minimum distance needed to complete the tour at the starting point, walking any road at most once.
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= ‘T’ <= 10
1 <= ‘N’ <= 10^3
0 <= ‘M’ <= min(10^3 , N*(N-1)/2 )
0 <= x[i], y[i] < N i ∈ (1,M)
Note - Sum of ‘N’ and Sum of ‘M’ over all test cases does not exceed 10^3.
Time Limit: 1 sec
Let’s assume that the given graph is a rooted tree (with loops), and each loop must have the root node in its path. For such cases, loops can be easily detected with BFS / DFS traversal. But the lengths of loops are also needed, so BFS is preferred.
While traversing the tree, if any node ‘x’ is visited more than once, then it’s in a loop, and the length of the loop will be [previous distance of node ‘x’ from root + current distance of ‘x’ from root].
Using the above assumption, we can find lengths of all loops passing through the ‘root’ node. Now, we take each vertex of the graph as the root node one by one and run a BFS traversal.
Algorithm: