A disconnected Graph with N vertices and K edges is given. The task is to find the count of singleton sub-graphs. A singleton graph is one with only single vertex.
Examples:
Input :
Vertices : 6
Edges : 1 2
1 3
5 6
Output : 1
Explanation : The Graph has 3 components : {1-2-3}, {5-6}, {4}
Out of these, the only component forming singleton graph is {4}.
The idea is simple for graph given as adjacency list representation. We traverse the list and find the indices(representing a node) with no elements in list, i.e. no connected components.
Below is the C++ representation :
// CPP code to count the singleton sub-graphs // in a disconnected graph #include <bits/stdc++.h> using namespace std; // Function to compute the count int compute(vector<int> graph[], int N) { // Storing intermediate result int count = 0; // Traversing the Nodes for (int i = 1; i <= N; i++) // Singleton component if (graph[i].size() == 0) count++; // Returning the result return count; } // Driver int main() { // Number of nodes int N = 6; // Adjacency list for edges 1..6 vector<int> graph[7]; // Representing edges graph[1].push_back(2); graph[2].push_back(1); graph[2].push_back(3); graph[3].push_back(2); graph[5].push_back(6); graph[6].push_back(5); cout << compute(graph, N); } |
Output:
1
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- BFS for Disconnected Graph
- Maximum and minimum isolated vertices in a graph
- Number of single cycle components in an undirected graph
- k'th heaviest adjacent node in a graph where each vertex has weight
- Minimum cost path from source node to destination node via an intermediate node
- Count number of edges in an undirected graph
- Level of Each node in a Tree from source node (using BFS)
- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Shortest path to reach one prime to other by changing single digit at a time
- Right sibling of each node in a tree given as array of edges
- Find all reachable nodes from every node present in a given set
- Number of loops of size k starting from a specific node
- Hypercube Graph
- Graph and its representations
- Dominant Set of a Graph



