📌  相关文章
📜  通过DFS方法计算无环图中两个顶点之间的节点数

📅  最后修改于: 2021-10-25 05:00:41             🧑  作者: Mango

给定一个由V个顶点和E 个边组成的连通无环图,一个源顶点src和一个目标顶点dest ,任务是计算图中给定源顶点和目标顶点之间的顶点数。

例子

方法:该问题也可以使用本文所述的不相交联合方法来解决。解决此问题的另一种方法是使用深度优先搜索方法来解决。请按照以下步骤解决此问题:

  • 初始化一个访问过的数组vis[]来标记哪些节点已经被访问过。将所有节点标记为0,即未访问。
  • 执行 DFS 以查找srcdest之间路径中存在的节点数
  • srcdest之间的节点数等于它们之间的路径长度与 2 之间的差值,即(pathSrcToDest – 2 )。
  • 由于该图是无环且连通的,因此srcdest之间始终只有一条路径

下面是上述算法的实现。

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to return the count of nodes
// in the path from source to destination
int dfs(int src, int dest, int* vis,
        vector* adj)
{
 
    // Mark the node visited
    vis[src] = 1;
 
    // If dest is reached
    if (src == dest) {
        return 1;
    }
 
    // Traverse all adjacent nodes
    for (int u : adj[src]) {
 
        // If not already visited
        if (!vis[u]) {
 
            int temp = dfs(u, dest, vis, adj);
 
            // If there is path, then
            // include the current node
            if (temp != 0) {
 
                return temp + 1;
            }
        }
    }
 
    // Return 0 if there is no path
    // between src and dest through
    // the current node
    return 0;
}
 
// Function to return the
// count of nodes between two
// given vertices of the acyclic Graph
int countNodes(int V, int E, int src, int dest,
               int edges[][2])
{
    // Initialize an adjacency list
    vector adj[V + 1];
 
    // Populate the edges in the list
    for (int i = 0; i < E; i++) {
        adj[edges[i][0]].push_back(edges[i][1]);
        adj[edges[i][1]].push_back(edges[i][0]);
    }
 
    // Mark all the nodes as not visited
    int vis[V + 1] = { 0 };
 
    // Count nodes in the path from src to dest
    int count = dfs(src, dest, vis, adj);
 
    // Return the nodes between src and dest
    return count - 2;
}
 
// Driver Code
int main()
{
    // Given number of vertices and edges
    int V = 8, E = 7;
 
    // Given source and destination vertices
    int src = 5, dest = 2;
 
    // Given edges
    int edges[][2]
        = { { 1, 4 }, { 4, 5 },
            { 4, 2 }, { 2, 6 },
            { 6, 3 }, { 2, 7 },
            { 3, 8 } };
 
    cout << countNodes(V, E, src, dest, edges);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.Vector;
class GFG{
 
// Function to return the count of nodes
// in the path from source to destination
static int dfs(int src, int dest, int []vis,
               Vector []adj)
{
  // Mark the node visited
  vis[src] = 1;
 
  // If dest is reached
  if (src == dest)
  {
    return 1;
  }
 
  // Traverse all adjacent nodes
  for (int u : adj[src])
  {
    // If not already visited
    if (vis[u] == 0)
    {
      int temp = dfs(u, dest,
                     vis, adj);
 
      // If there is path, then
      // include the current node
      if (temp != 0)
      {
        return temp + 1;
      }
    }
  }
 
  // Return 0 if there is no path
  // between src and dest through
  // the current node
  return 0;
}
 
// Function to return the
// count of nodes between two
// given vertices of the acyclic Graph
static int countNodes(int V, int E,
                      int src, int dest,
                      int edges[][])
{
  // Initialize an adjacency list
  Vector []adj = new Vector[V + 1];
  for (int i = 0; i < adj.length; i++)
    adj[i] = new Vector();
   
  // Populate the edges in the list
  for (int i = 0; i < E; i++)
  {
    adj[edges[i][0]].add(edges[i][1]);
    adj[edges[i][1]].add(edges[i][0]);
  }
 
  // Mark all the nodes as
  // not visited
  int vis[] = new int[V + 1];
 
  // Count nodes in the path
  // from src to dest
  int count = dfs(src, dest,
                  vis, adj);
 
  // Return the nodes
  // between src and dest
  return count - 2;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given number of vertices and edges
  int V = 8, E = 7;
 
  // Given source and destination vertices
  int src = 5, dest = 2;
 
  // Given edges
  int edges[][] = {{1, 4}, {4, 5},
                   {4, 2}, {2, 6},
                   {6, 3}, {2, 7},
                   {3, 8}};
 
  System.out.print(countNodes(V, E,
                              src, dest,
                              edges));
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
 
# Function to return the count of nodes
# in the path from source to destination
def dfs(src, dest, vis, adj):
 
    # Mark the node visited
    vis[src] = 1
 
    # If dest is reached
    if (src == dest):
        return 1
 
    # Traverse all adjacent nodes
    for u in adj[src]:
 
        # If not already visited
        if not vis[u]:
            temp = dfs(u, dest, vis, adj)
 
            # If there is path, then
            # include the current node
            if (temp != 0):
                return temp + 1
 
    # Return 0 if there is no path
    # between src and dest through
    # the current node
    return 0
 
# Function to return the
# count of nodes between two
# given vertices of the acyclic Graph
def countNodes(V, E, src, dest, edges):
     
    # Initialize an adjacency list
    adj = [[] for i in range(V + 1)]
 
    # Populate the edges in the list
    for i in range(E):
        adj[edges[i][0]].append(edges[i][1])
        adj[edges[i][1]].append(edges[i][0])
 
    # Mark all the nodes as not visited
    vis = [0] * (V + 1)
 
    # Count nodes in the path from src to dest
    count = dfs(src, dest, vis, adj)
 
    # Return the nodes between src and dest
    return count - 2
 
# Driver Code
if __name__ == '__main__':
     
    # Given number of vertices and edges
    V = 8
    E = 7
 
    # Given source and destination vertices
    src = 5
    dest = 2
 
    # Given edges
    edges = [ [ 1, 4 ], [ 4, 5 ],
              [ 4, 2 ], [ 2, 6 ],
              [ 6, 3 ], [ 2, 7 ],
              [ 3, 8 ] ]
 
    print(countNodes(V, E, src, dest, edges))
 
# This code is contributed by mohit kumar 29


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return the count of nodes
// in the path from source to destination
static int dfs(int src, int dest,
               int []vis, List []adj)
{
  // Mark the node visited
  vis[src] = 1;
 
  // If dest is reached
  if (src == dest)
  {
    return 1;
  }
 
  // Traverse all adjacent nodes
  foreach (int u in adj[src])
  {
    // If not already visited
    if (vis[u] == 0)
    {
      int temp = dfs(u, dest,
                     vis, adj);
 
      // If there is path, then
      // include the current node
      if (temp != 0)
      {
        return temp + 1;
      }
    }
  }
 
  // Return 0 if there is no path
  // between src and dest through
  // the current node
  return 0;
}
 
// Function to return the
// count of nodes between two
// given vertices of the acyclic Graph
static int countNodes(int V, int E,
                      int src, int dest,
                      int [,]edges)
{
  // Initialize an adjacency list
  List []adj = new List[V + 1];
   
  for (int i = 0; i < adj.Length; i++)
    adj[i] = new List();
   
  // Populate the edges in the list
  for (int i = 0; i < E; i++)
  {
    adj[edges[i, 0]].Add(edges[i, 1]);
    adj[edges[i, 1]].Add(edges[i, 0]);
  }
 
  // Mark all the nodes as
  // not visited
  int []vis = new int[V + 1];
 
  // Count nodes in the path
  // from src to dest
  int count = dfs(src, dest,
                  vis, adj);
 
  // Return the nodes
  // between src and dest
  return count - 2;
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given number of vertices and edges
  int V = 8, E = 7;
 
  // Given source and destination vertices
  int src = 5, dest = 2;
 
  // Given edges
  int [,]edges = {{1, 4}, {4, 5},
                  {4, 2}, {2, 6},
                  {6, 3}, {2, 7},
                  {3, 8}};
 
  Console.Write(countNodes(V, E, src,
                           dest, edges));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
1

时间复杂度: O(V+E)
辅助空间: O(V)

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