VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-of-maximum-distance-to-colored-vertices/

⇱ Minimum of Maximum Distance to Colored Vertices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum of Maximum Distance to Colored Vertices

Last Updated : 20 Mar, 2024

Given a tree of N vertices, where a vertex can be colored or uncolored, the task is to determine for each vertex the maximum distance to any of the colored vertices. The task is to find the minimum value among all maximumdistances for vertices.

Example:

Input:
1
/ \
2 3
/ \ / \
4 5 6 7

marked[] = {2, 6, 7}

Output: 2

Explanation: The maximum distance for each vertex are: [2,3,2,4,4,3,3], minimum is 2

Input:

1
/ \
2 3
/
4

marked[] = {4}

Output: 0

Explanation: The maximum distance for each vertex are: [2,1,3,0], minimum is 0.

Approach: To solve the problem, follow the idea below:

The idea lies in the observation that only the marked vertex at the extreme positions will contribute to the answer because the vertex between them will have the minimum distance from marked vertex. Therefore, we just have to return the ceil of distance between two extreme vertex / 2. To find the distance between marked vertices at extreme ends find the distance of all vertices from the first vertex by BFS. Find the farthest marked node from the first node. Then from the farthest marked node found, using BFS find the other farthest marked node.

Step-by-step algorithm:

  • If there’s only one marked node, print 0 as the distance to itself will be 0.
  • Perform Breadth-First Search (BFS) from the first node.
  • Find the farthest marked node from the first node.
  • Perform BFS from the farthest marked node found in the previous step.
  • Find the farthest marked node from the previously found farthest marked node.
  • Print the maximum distance ,i.e the distance between the two farthest node, divided by 2.

Below is the implementation of the algorithm:


Output
2
0

Time Complexity: O(N), where N is the number of nodes in the tree.
Auxiliary Space: O(N)

Comment
Article Tags: