unoriented graph

Mark invented facebook, meanwhile some people created friendships, he doesnt want to waste time so he creates a machine which sends a message to people and the message needs to get to everyone. ( here I explain the problem a little so you dont waste time : for each Connected component you need to choose a node so the message gets delivered the fastest way to everyone. This is the second task and the first one is to find the minimum amount of people that need to get the message so everyone gets the message (from those people) , (this is easy DFS for amount of connected components), returning to the second task, Ill try explaining it with a example , the input is n, m , following m lines describe friendships :
1 <= n <= 5000
1 <= m <= 1000000 
1 <= X < Y <= n
time limit : 0.1 s
Input :
8 6
1 2
2 4
2 5
3 7
4 8
6 7

OutPut : 2 3

2 (first task , number of connected components) and 3 the minimum time everyone gets the message, I know that by now you still dont know how the minimum time is calculated so let me explain this example :
as I said before ,for task 2 you have to choose one person from each connected component to give the message to him, and in the end the minimum time is the shortest time in which everyone gets the message
for the example you pick node 2 and 7 (when you pick a node the time becomes 1 because it takes 1 second when you pick the node) , so from these nodes , the nodes 1,5,4,3,6 recieve the message in the 2 second and in the 3 second the node 4 tells the message to node 8. now everyone got the message and the minimum time obtained was 3.
This is it, dont tell me that you cant understand it from the example because thats what I did because the text of the problem was not giving much information at all.
my code got 90/100 for "time limit excedeed" and im curios how to efficentize it.
Thanks so much if you take the time to help me.
my code : https://pastebin.com/jTfSseRN
Topic archived. No new replies allowed.