简体   繁体   English

如何使用邻接矩阵计算孤立顶点的数量

[英]How to calculate amount of isolated vertices using adjacency matrix

I've got stuck with the problem of counting amount of isolated vertices in the graph.我遇到了计算图中孤立顶点数量的问题。 Below you will see the code下面你会看到代码

#include <iostream>
#include <vector>
#define V 4 // amount of vertices in the graph 
// Function to add edge between vertices
void addEdge(std::vector<int> adj[V], int u, int v)
{
   adj[u].push_back(v);
   adj[v].push_back(u);
}
// Function to count amount of isolated vertices in graph with return type int
int FindIsolated(std::vector<int> adj[V])
{
   int isolated = 0; // counter to save amount of isolated vertices
   for(int v = 0; v < V; ++v)
   {
      for(auto x: adj[v])
      {
         if(x == 0)
         {
            isolated++;
         }
      }
   }
    return isolated;
}
// Driver code
int main()
{
   std::vector<int> adj[V];
   addEdge(adj, 1, 2);
   addEdge(adj, 1, 3);
   addEdge(adj, 0, 0);
   std::cout << "This graph contains " << FindIsolated(adj) << " isolated vertices" << std::endl;
   std::cin.get();
   return 0;
}

In the output I have a message: "This graph contains 2 isolated vertices" but I need the message "This graph contains 1 isolated vertices" Any suggestions and describing the solution is appreciated.在输出中,我有一条消息:“此图包含 2 个隔离顶点”但我需要消息“此图包含 1 个隔离顶点”任何建议和描述解决方案都值得赞赏。 Thank you :)谢谢 :)

void addEdge(std::vector<int> adj[V], int u, int v)
{
   adj[u].push_back(v);
   adj[v].push_back(u);
}

This is going to give you problems!!!!这会给你带来麻烦!!!! It should not even compile!!!!!!!!!!!!!!!它甚至不应该编译!!!!!!!!!!!!!!!

adj[u] is an integer, not a vector. adj[u] 是一个整数,而不是一个向量。 adj[u].push_back(v); makes no sense没有意义


Normally a adjacency matrix is used for this通常使用邻接矩阵

Like so像这样

void addEdge(
   std::vector<std::vector<<int>>& adj,
   int u, int v)
{
   adj[u].push_back(v);
   adj[v].push_back(u);
}

@aschepler points out you are using an unusual syntax to define your matrix. @aschepler 指出您正在使用一种不寻常的语法来定义您的矩阵。 Please do not do this.请不要这样做。


This is wrong这是错误的

  for(int v = 0; v < V; ++v)
   {
      for(auto x: adj[v])
      {
         if(x == 0)
         {
            isolated++;
         }
      }
   }

Should be应该

  for(int v = 0; v < V; ++v)
   {
      if( ! adj[v].size() )
            isolated++;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM