Pairing (Graphs) - TLE

Getting TLE in three test cases.

Your code is having a Time Complexity of O(n * n*(n+m)),where n are the number of edges.
Lets see how:As you are using for into for over the size of list wherein list have size=n,and inside n you are calling hasPath which itself have time complexity of n m,
Total=n * n
(n+m).
Now we have to do in nlogn or n.
What we can think is,the number of ways of selecting a pair is similar to getting connected components in a Graph .Let me elaborate further,
Consider 5 3
0 1
2 3
0 4

Here,by drawing on paper we can see 4-0-1 and 2-3 are two connected components of size 3 and 2 respectively,hence 3*2 are total ways .
This approach will reduce time complexity to O(m+n).
Please Refer this:https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/

I have used this method by using the function getConnectedComponents() which will return me a 2D list of all the connected components and multiply the sizes but that method failed in the case when we have some vertices that are isolated.

Here is my code. Please check this.