Minimum of the Maximum distances from any node to all other nodes of given Tree
Given a tree with N vertices and N-1 edges represented by a 2D array edges[], the task is to find the minimum value among the maximum distances from any node to all other nodes of the tree.
Examples:
Input: N = 4, edges[] = { {1, 2}, {2, 3}, {2, 4} }
Output: 1
Explanation: The Tree looks like the following.
2
/ | \
1 3 4
Maximum distance from house number 1 to any other node is 2.
Maximum distance from house number 2 to any other node is 1.
Maximum distance from house number 3 to any other node is 2.
Maximum distance from house number 4 to any other node is 2.
The minimum among these is 1.Input: N = 10, edges[] = { {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {7, 8}, {8, 9}, {9, 10} }
Output: 5
Approach: This problem can be solved using Depth First Search based on the following idea:
For each node find the farthest node and the distance to that node. Then find the minimum among those values.
Follow the steps mentioned below to implement the idea:
- Create a distance array (say d[]) where d[i] stores the maximum distance to all other nodes from the ith node.
- For every node present in the tree consider each of them as the source one by one:
- Mark the distance of the source from the source as zero.
- Find the maximum distance of all other nodes from the source.
- Find the minimum value among these maximum distances.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to run DFSvoid dfs(vector<int>& d, int node, vector<vector<int> >& adj, int dist){ d[node] = dist; // DFS call fro all its neighbours for (auto child : adj[node]) { if (dist + 1 < d[child]) dfs(d, child, adj, dist + 1); }} // Function to find the minimum distanceint minDist(int N, vector<vector<int> >& edges){ int ans = INT_MAX; // Creation of the adjacency matrix vector<vector<int> > adj(N + 1); for (auto u : edges) { adj[u[0]].push_back(u[1]); adj[u[1]].push_back(u[0]); } // Consider ith node as source // in each iteration for (int i = 1; i <= N; i++) { // Distance array to store // distance of all the nodes // from source vector<int> d(N + 1, INT_MAX); // DFS traversal of the tree and store // distance of all nodes from source dfs(d, i, adj, 0); int dist = 0; // Find max distance from distance array for (int j = 1; j <= N; j++) dist = max(dist, d[j]); // If distance found is smaller than ans // then make ans equal to distance ans = min(ans, dist); } // Return the minimum value return ans;} // Driver Codeint main(){ int N = 4; vector<vector<int> > edges = { { 1, 2 }, { 2, 3 }, { 2, 4 } }; // Function call cout << minDist(N, edges); return 0;} |
1
Time Complexity: O(N*N)
Auxiliary Space: O(N)


