
Let the number of fruits be 4 i.e. N = 4 and the list of pair of fruit ids be { [0, 2], [2, 3] }. From the given list we can say that there are 2 boxes of fruits: [0, 2, 3] and [1]. Therefore Ninja can select two fruits which belong to different boxes as [1, 0], [1, 2], and [1, 3] i.e. a total of 3 ways.
The very first line of input contains an integer T’ denoting the number of test cases.
The first line of every test case contains two space-separated integers ‘N’ and ‘M’ denoting the number of fruits and the number of pairs of fruit ids in the list, respectively.
Each of the next ‘M’ lines contains two space-separated integers ‘u’ and ‘v’ denoting the pairs of fruit ids of the fruits which are placed in the same box.
For each test case, print the number of ways Ninja can select two fruits that belong to different boxes.
Output for each test case is printed on a separate line.
You do not need to print anything, it has already been taken care of. Just return the number of ways.
1 <= T <= 10
2 <= N <= 5 * 10^4
1 <= M < N-1
0 <= Fruit ID <= N-1
Time Limit: 1 sec
Where ‘T’ represents the number of test cases and ‘N’ represents the number of fruits and ‘M’ represents the number of pairs of fruit ids in the list.
In the above approach, we have used DFS to check reachability. You can also use BFS, but the idea will remain the same.
In the above approach, we have used DFS to find the connected components. You can also use BFS, but the idea will remain the same.