How to calculate amount of isolated vertices using adjacency matrix

206 Views Asked by At

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. Thank you :)

1

There are 1 best solutions below

1
ravenspoint On
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].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. 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++;
   }