![]() |
VOOZH | about |
Given a weighted undirected graph T consisting of nodes valued [0, N - 1] and an array Edges[][3] of type {u, v, w} that denotes an edge between vertices u and v having weight w. The task is to find the sum of all pair shortest paths in the given tree.
Examples:
Input: N = 3, Edges[][] = {{0, 2, 15}, {1, 0, 90}}
Output: 210
Explanation:
Sum of weights of path between nodes 0 and 1 = 90
Sum of weights of path between nodes 0 and 2 = 15
Sum of weights of path between nodes 1 and 2 = 105
Hence, sum = 90 + 15 + 105Input: N = 4, Edges[][] = {{0, 1, 1}, {1, 2, 2}, {2, 3, 3}}
Output: 20
Explanation:
Sum of weights of path between nodes 0 and 1 = 1
Sum of weights of path between nodes 0 and 2 = 3
Sum of weights of path between nodes 0 and 3 = 6
Sum of weights of path between nodes 1 and 2 = 2
Sum of weights of path between nodes 1 and 3 = 5
Sum of weights of path between nodes 2 and 3 = 3
Hence, sum = 1 + 3 + 6 + 2 + 5 + 3 = 20.
Naive Approach: The simplest approach is to find the shortest path between every pair of vertices using the Floyd Warshall Algorithm. After precomputing the cost of the shortest path between every pair of nodes, print the sum of all the shortest paths.
Below is the implementation of the above approach:
20
Time Complexity:O(N3), where N is the number of vertices.
Auxiliary Space: O(N)
Efficient Approach: The idea is to usethe DFS algorithm, using the DFS, for each vertex, the cost to visit every other vertex from this vertex can be found in linear time. Follow the below steps to solve the problem:
Below is the implementation of the above approach:
20
Time Complexity: O(N2), where N is the number of vertices.
Auxiliary Space: O(N)