Given an Undirected Connected Graph in the form of a tree consisting of N nodes and (N – 1) edges, the task for each edge is to count the number of times it appears across all possible paths in the Tree.
Examples:
Input:
Output:_ 3 4 3 _
Explanation:
_All possible paths of a given tree are {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} _
_Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4)}. Therefore, the frequency of the edge is 3. _
_Edge 2 occurs in the paths {(1, 3), (1, 4), (2, 3), (2, 4)}. Therefore, the frequency of the edge is 4. _
Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4)}. Therefore, the frequency of the edge is 3.
Input:
Output:_ 4 6 4 4 _
Explanation:
_Edge 1 occurs in the paths {(1, 2), (1, 3), (1, 4), (1, 5)}. Therefore, the frequency of the edge is 4 _
_Edge 2 occurs in the paths {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}. Therefore, the frequency of the edge is 6 _
_Edge 3 occurs in the paths {(1, 4), (2, 4), (3, 4), (4, 5)}. Therefore, the frequency of the edge is 4 _
_Edge 4 occurs in the paths {(1, 5), (2, 5), (3, 5), (4, 5)}. Therefore, the frequency of the edge is 4 _
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Naive Approach: The simplest approach is to generate all possible paths from each node of the given graph and store the count of edges occurring in these paths by a HashMap. Finally, print the frequencies of each edges.
#data structures #graph #hash #tree #dfs #big data