Minimum of the Maximum distances from any node to all other nodes of given Tree
Last Updated :
05 Dec, 2022
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 DFS
void dfs(vector<int>& d, int node,
vector<vector<int> >& adj, int dist)
{
d[node] = dist;
// DFS call for all its neighbours
for (auto child : adj[node]) {
if (dist + 1 < d[child])
dfs(d, child, adj, dist + 1);
}
}
// Function to find the minimum distance
int 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 Code
int main()
{
int N = 4;
vector<vector<int> > edges
= { { 1, 2 }, { 2, 3 }, { 2, 4 } };
// Function call
cout << minDist(N, edges);
return 0;
}
Java
// Java code to implement the above approach
import java.util.ArrayList;
public class GFG {
// Function to run DFS
static void dfs(int[] d, int node,
ArrayList<Integer>[] adj, int dist)
{
d[node] = dist;
// DFS call for all its neighbours
for (int child : adj[node]) {
if (dist + 1 < d[child])
dfs(d, child, adj, dist + 1);
}
}
// Function to find the minimum distance
@SuppressWarnings("unchecked")
static int minDist(int N, int[][] edges)
{
int ans = Integer.MAX_VALUE;
// Creation of the adjacency matrix
ArrayList<Integer>[] adj = new ArrayList[N + 1];
for (int i = 0; i <= N; i++)
adj[i] = new ArrayList<Integer>();
for (int[] u : edges) {
adj[u[0]].add(u[1]);
adj[u[1]].add(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
int[] d = new int[N + 1];
for (int j = 0; j <= N; j++)
d[j] = Integer.MAX_VALUE;
// 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 = Math.max(dist, d[j]);
// If distance found is smaller than ans
// then make ans equal to distance
ans = Math.min(ans, dist);
}
// Return the minimum value
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
int[][] edges = { { 1, 2 }, { 2, 3 }, { 2, 4 } };
// Function call
System.out.println(minDist(N, edges));
}
}
// This code is contributed by Lovely Jain
Python3
# Python code to implement the above approach
# Function to run DFS
import sys
def dfs(d, node, adj, dist):
d[node] = dist
# DFS call for all its neighbours
for child in adj[node]:
if (dist + 1 < d[child]):
dfs(d, child, adj, dist + 1)
# Function to find the minimum distance
def minDist(N, edges):
ans = sys.maxsize
# Creation of the adjacency matrix
adj = [[] for i in range(N+1)]
for u in edges:
adj[u[0]].append(u[1])
adj[u[1]].append(u[0])
# Consider ith node as source
# in each iteration
for i in range(1,N+1):
# Distance array to store
# distance of all the nodes
# from source
d = [sys.maxsize for i in range(N+1)]
# DFS traversal of the tree and store
# distance of all nodes from source
dfs(d, i, adj, 0)
dist = 0
# Find max distance from distance array
for j in range(1,N+1):
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 Code
N = 4
edges = [[1, 2], [2, 3], [2, 4]]
# Function call
print(minDist(N, edges))
# This code is contributed by shinjanpatra
C#
// C# code to implement the above approach
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
// Function to run DFS
static void dfs(int[] d, int node, List<int>[] adj,
int dist)
{
d[node] = dist;
// DFS call for all its neighbours
foreach(int child in adj[node])
{
if (dist + 1 < d[child])
dfs(d, child, adj, dist + 1);
}
}
// Function to find the minimum distance
static int minDist(int N, int[, ] edges)
{
int ans = Int32.MaxValue;
// Creation of the adjacency matrix
List<int>[] adj = new List<int>[ N + 1 ];
for (int i = 0; i <= N; i++)
adj[i] = new List<int>();
for (int i = 0; i < edges.GetLength(0); i++) {
int[] u = { edges[i, 0], edges[i, 1] };
adj[u[0]].Add(u[1]);
adj[u[1]].Add(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
int[] d = new int[N + 1];
for (int j = 0; j <= N; j++)
d[j] = Int32.MaxValue;
// 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 = Math.Max(dist, d[j]);
// If distance found is smaller than ans
// then make ans equal to distance
ans = Math.Min(ans, dist);
}
// Return the minimum value
return ans;
}
// Driver Code
public static void Main(string[] args)
{
int N = 4;
int[, ] edges = { { 1, 2 }, { 2, 3 }, { 2, 4 } };
// Function call
Console.WriteLine(minDist(N, edges));
}
}
// This code is contributed by karandeep1234.
JavaScript
<script>
// Javascript code to implement the above approach
// Function to run DFS
function dfs(d, node, adj, dist) {
d[node] = dist;
// DFS call for all its neighbours
for (let child of adj[node]) {
if (dist + 1 < d[child])
dfs(d, child, adj, dist + 1);
}
}
// Function to find the minimum distance
function minDist(N, edges) {
let ans = Number.MAX_SAFE_INTEGER;
// Creation of the adjacency matrix
let adj = new Array(N + 1).fill(0).map(() => new Array());
for (let u of edges) {
adj[u[0]].push(u[1]);
adj[u[1]].push(u[0]);
}
// Consider ith node as source
// in each iteration
for (let i = 1; i <= N; i++) {
// Distance array to store
// distance of all the nodes
// from source
let d = new Array(N + 1).fill(Number.MAX_SAFE_INTEGER);
// DFS traversal of the tree and store
// distance of all nodes from source
dfs(d, i, adj, 0);
let dist = 0;
// Find max distance from distance array
for (let j = 1; j <= N; j++)
dist = Math.max(dist, d[j]);
// If distance found is smaller than ans
// then make ans equal to distance
ans = Math.min(ans, dist);
}
// Return the minimum value
return ans;
}
// Driver Code
let N = 4;
let edges = [[1, 2], [2, 3], [2, 4]];
// Function call
document.write(minDist(N, edges));
// This code is contributed by gfgking.
</script>
Time Complexity: O(N*N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read