You are given an undirected unweighted graph such that there are no loops in this graph and it is strongly connected and there are always (vertices-1) edges in the graph. For each node, you need to find the sum of the distance of all other nodes from the given node.
Distance between any two nodes is the number of edges between the two given nodes.
The first line of input contains an integer 'T', the number of test cases.
The first line of the test case contains a single integer ‘N’.
From the second line onwards next 'N-1' lines denote the edges of the graph.
Each edge is characterized by two integers 'A' and 'B' where 'A' and 'B' denote the endpoints of the edge. The edges[i][0], edges[i][1] contains the endpoints of edges.
Output Format:
For each test case, return the list where the ith element denotes the distance of the ith vertex from all others vertices.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N <= 10^3
0 <= edges[i][0], edges[i][1] <= N-1
Total number of edges = N-1
Time Limit: 1 sec
2
5
0 4
3 1
3 2
0 3
3
0 1
0 2
6 8 8 5 9
2 3 3
For first test-case the graph will be :-
The distance between 0 and 1 is 2
Distance between 0 and 2 is 2
Distance between 0 and 4 and 0 and 3 is 1
So ans[0]=2+2+1+1=6
Similarly, it can be calculated for others.
2
6
0 4
3 1
3 2
0 3
3 5
2
0 1
8 10 10 6 12 10
1 1
Use bfs/dfs from each vertex to find the distance from all vertices.
The key idea is to apply bfs/dfs from each vertex to find distance from all vertices.
Algorithm:
O(N^2), where ‘N’ is the number of given nodes.
We run a dfs/bfs from every vertex.The bfs/dfs traversal takes O(n) time. Thus total time complexity is O(N^2).
O(N), where ‘N’ is the number of given nodes.
In every dfs/bfs traversal we create distance array of size n which stores distance. Thus space complexity is O(N).