📌  相关文章
📜  图中最远节点的距离最小值

📅  最后修改于: 2021-10-25 03:32:30             🧑  作者: Mango

给定一个具有N 个节点和N-1 条边的无环无向图,采用二维数组arr[][] 的形式,其中每行由两个数字L 和 R组成,它们表示L 和 R之间的边。对于树中的每个节点X ,令dis(X)表示从X到最远节点的边数。任务是找到给定图的dis(x)的最小值。

例子:

方法:
思路是使用DFS Traversal来解决这个问题。以下是步骤:

  1. 对于任何节点(例如a ),使用 DFS 遍历以节点与自身的距离为 0 来遍历图。
  2. 对于节点a 的每次递归调用,不断更新递归节点与数组中节点a距离(比如distance[] )。
  3. 通过对 Node a 的每次递归调用取距离的最大值,给出节点a与其最远节点之间的边数。
  4. 对图中的所有节点重复上述步骤,并不断更新距离数组中每个节点的最远节点距离( distance[] )。
  5. 数组distance[]的最小值就是想要的结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Distance vector to find the distance of
// a node to it's farthest node
vector dist;
 
// To keep the track of visited array
// while DFS Traversal
vector vis;
 
// Function for DFS traversal to update
// the distance vector
void dfs(int u, vector Adj[], int s)
{
    // Mark the visited array for vertex u
    vis[u] = true;
 
    // Traverse the adjacency list for u
    for (auto& it : Adj[u]) {
 
        // If the any node is not visited,
        // then recursively call for next
        // vertex with distance increment
        // by 1
        if (vis[it] == false) {
            dfs(it, Adj, s + 1);
        }
    }
 
    // Update the maximum distance for the
    // farthest vertex from node u
    dist[u] = max(dist[u], s);
}
 
// Function to find the minimum of the
// farthest vertex for every vertex in
// the graph
void minFarthestDistance(int arr[][2], int n)
{
 
    // Resize distance vector
    dist.resize(n + 1, 0);
 
    // To create adjacency list for graph
    vector Adj[n + 1];
 
    // Create Adjacency list for every
    // edge given in arr[][]
    for (int i = 0; i < n - 1; i++) {
        Adj[arr[i][0]].push_back(arr[i][1]);
        Adj[arr[i][1]].push_back(arr[i][0]);
    }
 
    // DFS Traversal for every node in the
    // graph to update the distance vector
    for (int i = 1; i <= n; i++) {
 
        // Clear and resize vis[] before
        // DFS traversal for every vertex
        vis.clear();
        vis.resize(n + 1, false);
 
        // DFS Traversal for vertex i
        dfs(i, Adj, 0);
    }
 
    cout << *min_element(dist.begin() + 1,
                         dist.end());
}
 
// Driver Code
int main()
{
    // Number of Nodes
    int N = 6;
    int arr[][2] = { { 1, 4 }, { 2, 3 }, { 3, 4 },
                     { 4, 5 }, { 5, 6 } };
 
    minFarthestDistance(arr, N);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Distance vector to find the distance
// of a node to it's farthest node
static int[] dist;
 
// To keep the track of visited array
// while DFS Traversal
static boolean[] vis;
 
// Function for DFS traversal to update
// the distance vector
static void dfs(int u, Vector[] Adj, int s)
{
     
    // Mark the visited array for vertex u
    vis[u] = true;
 
    // Traverse the adjacency list for u
    for (int it : Adj[u])
    {
         
        // If the any node is not visited,
        // then recursively call for next
        // vertex with distance increment
        // by 1
        if (vis[it] == false)
        {
            dfs(it, Adj, s + 1);
        }
    }
 
    // Update the maximum distance for
    // the farthest vertex from node u
    dist[u] = Math.max(dist[u], s);
}
 
// Function to find the minimum of the
// farthest vertex for every vertex in
// the graph
static void minFarthestDistance(int[][] arr, int n)
{
     
    // Resize distance vector
    dist = new int[n + 1];
    Arrays.fill(dist, 0);
 
    // To create adjacency list for graph
    @SuppressWarnings("unchecked")
    Vector[] Adj = new Vector[n + 1];
 
    for(int i = 0; i < n + 1; i++)
    {
        Adj[i] = new Vector<>();
    }
 
    // Create Adjacency list for every
    // edge given in arr[][]
    for(int i = 0; i < n - 1; i++)
    {
        Adj[arr[i][0]].add(arr[i][1]);
        Adj[arr[i][1]].add(arr[i][0]);
    }
 
    // DFS Traversal for every node in the
    // graph to update the distance vector
    for(int i = 1; i <= n; i++)
    {
         
        // Clear and resize vis[] before
        // DFS traversal for every vertex
        vis = new boolean[n + 1];
        Arrays.fill(vis, false);
 
        // DFS Traversal for vertex i
        dfs(i, Adj, 0);
    }
 
    int min = Integer.MAX_VALUE;
    for(int i = 1; i < dist.length; i++)
    {
        if (dist[i] < min)
            min = dist[i];
    }
    System.out.println(min);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Number of Nodes
    int N = 6;
    int[][] arr = { { 1, 4 }, { 2, 3 },
                    { 3, 4 }, { 4, 5 },
                    { 5, 6 } };
 
    minFarthestDistance(arr, N);
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 program for the above approach
 
# Function for DFS traversal to update
# the distance vector
def dfs(u, s):
     
    global vis, Adj, dist
 
    # Mark the visited array for vertex u
    vis[u] = True
 
    # Traverse the adjacency list for u
    for it in Adj[u]:
         
        # If the any node is not visited,
        # then recursively call for next
        # vertex with distance increment
        # by 1
        if (vis[it] == False):
            dfs(it, s + 1)
 
    # Update the maximum distance for the
    # farthest vertex from node u
    dist[u] = max(dist[u], s)
 
# Function to find the minimum of the
# farthest vertex for every vertex in
# the graph
def minFarthestDistance(arr, n):
     
    global dist, vis, Adj
     
    # Create Adjacency list for every
    # edge given in arr[][]
    for i in range(n - 1):
        Adj[arr[i][0]].append(arr[i][1])
        Adj[arr[i][1]].append(arr[i][0])
 
    # DFS Traversal for every node in the
    # graph to update the distance vector
    for i in range(1, n + 1):
         
        # Clear and resize vis[] before
        # DFS traversal for every vertex
        # vis.clear()
        for j in range(n + 1):
            vis[j] = False
             
        # vis.resize(n + 1, false)
 
        # DFS Traversal for vertex i
        dfs(i, 0)
 
    print(min(dist[i] for i in range(1, n + 1)))
 
# Driver Code
if __name__ == '__main__':
     
    dist = [0 for i in range(1001)]
    vis = [False for i in range(1001)]
    Adj = [[] for i in range(1001)]
 
    # Number of Nodes
    N = 6
    arr = [ [ 1, 4 ], [ 2, 3 ],
            [ 3, 4 ], [ 4, 5 ], [ 5, 6 ] ]
 
    minFarthestDistance(arr, N)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Distance vector to find the distance
  // of a node to it's farthest node
  static int[] dist;
 
  // To keep the track of visited array
  // while DFS Traversal
  static bool[] vis;
 
  // Function for DFS traversal to update
  // the distance vector
  static void dfs(int u, List> Adj, int s)
  {
 
    // Mark the visited array for vertex u
    vis[u] = true;
 
    // Traverse the adjacency list for u
    foreach(int it in Adj[u])
    {
 
      // If the any node is not visited,
      // then recursively call for next
      // vertex with distance increment
      // by 1
      if (vis[it] == false)
      {
        dfs(it, Adj, s + 1);
      }
    }
 
    // Update the maximum distance for
    // the farthest vertex from node u
    dist[u] = Math.Max(dist[u], s);       
  }
 
  // Function to find the minimum of the
  // farthest vertex for every vertex in
  // the graph
  static void minFarthestDistance(int[,] arr, int n)
  {
 
    // Resize distance vector
    dist = new int[n + 1];
    Array.Fill(dist, 0);
 
    // To create adjacency list for graph
    List> Adj = new List>();
    for(int i = 0; i < n + 1; i++)
    {
      Adj.Add(new List());
    }
 
    // Create Adjacency list for every
    // edge given in arr[][]
    for(int i = 0; i < n - 1; i++)
    {
      Adj[arr[i, 0]].Add(arr[i, 1]);
      Adj[arr[i, 1]].Add(arr[i, 0]);
    }
 
    // DFS Traversal for every node in the
    // graph to update the distance vector
    for(int i = 1; i <= n; i++)
    {
 
      // Clear and resize vis[] before
      // DFS traversal for every vertex
      vis = new bool[n + 1];
      Array.Fill(vis, false);
 
      // DFS Traversal for vertex i
      dfs(i, Adj, 0);
    }
    int min = Int32.MaxValue;
    for(int i = 1; i < dist.Length; i++)
    {
      if (dist[i] < min)
      {
        min = dist[i];
      }
 
    }
    Console.WriteLine(min);  
  }
 
  // Driver Code
  static public void Main ()
  {
 
    // Number of Nodes
    int N = 6;
    int[,] arr = { { 1, 4 }, { 2, 3 },{ 3, 4 },
                  { 4, 5 }, { 5, 6 } };
    minFarthestDistance(arr, N);
  }
}
 
// This code is contributed by rag2127


Javascript


输出:
2

时间复杂度: O(V*(V+E)),其中 V 是顶点数,E 是边数。
辅助空间: O(V + E)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程