![]() |
VOOZH | about |
Given an undirected tree consisting of n vertices and n-1 edges. The task is to add the minimum number of edges in such a way that the length of the shortest path from vertex 1 to any other vertex is at most 2. The edges should be added in a way that the graph does not contain any loops.
Example:
Input: n = 7, edges = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {4, 6}, {5, 7}}
Output: 2Input: n = 7, edges = {{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 6}, {1, 7}}
Output: 0
Approach:
The idea is to perform a Depth-First Search (DFS) on an undirected tree to calculate the distance of each vertex from the root. It then identifies vertices whose distance from the root exceeds 2 and removes them along with their neighbors iteratively until the resulting graph satisfies the condition of having a minimum shortest path of at most 2 from vertex 1 to any other vertex. The count of removed vertices and their neighbors represents the minimum number of edges to be added to meet the given criteria.
Step-by-step approach:
Below is the implementation of the above approach:
2
Time Complexity: O(n log n)
Auxiliary Space: O(n).