
There are no parallel edges and self-loops in the graph given by Gwen.
A tree is a connected graph having no cycles.
The first line of input contains an integer 'T' representing the number of test cases.
The first line of each test case contains two space-separated integers ‘N’ and ‘M’. Here ‘N’ denotes the total number of nodes and ‘M’ denotes the total number of edges in the graph given by Gwen.
The next ‘M’ lines contain two space-separated integers ‘U’ and ‘V’. Here ‘U’ and ‘V’ represent the nodes that share an edge between them.
For each test case, print 1 if the graph given by Gwen is a tree, else you need to print 0.
The output of each test case will be printed in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 5000
1 <= M <= min(5000, N*(N-1)/2)
1 <= U, V<= N - 1
The idea here is to check to use the fact that Tree is a connected graph having no cycles. For a graph to be connected it must have only one connected component. We can check both of these conditions using dfs.
We will run dfs starting from node zero and if all nodes are not visited then it means that we cannot reach a node from node number zero. So it shows that the graph is disconnected.
To check for the cycle we need to check whether the given graph contains a back-edge or not. If the graph doesn’t contain a back edge then it means it does not contain a cycle.
Consider the below example for better understanding.
In the above figure, we start dfs from node 0 and visit node 1, 2, 6 respectively (visited nodes are marked red). After reaching 6 we have found that node 6 has one more parent other than 2 which is 3. So the edge between 3 and 6 is back-edge. It is telling us that there is also another path through which we can reach 6 other than our current dfs path that is 0-> 3 -> 6. So we can go back to start node 0 from 6 using path 6 -> 3 -> 0. So it will create a cycle of 0->1->2->6->3->0.
Algorithm:
Description of DFS function :
We will use the same idea that we used in the previous approach. We will look for cycles in the graph. This time we will use bfs to check cycles. We will maintain parents of all nodes in an array and if we can find a back-edge then it will tell us that the graph contains a cycle. Also After running bfs if there remains an unvisited node then it shows the graph is disconnected. If our graph is connected and doesn’t contain a cycle then it will be a tree.
Algorithm:
Description of BFS function :
bool bfs (graph, visited) :