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 representation :
C++
#include <bits/stdc++.h>
using namespace std;
int compute(vector<int> graph[], int N)
{
int count = 0;
for (int i = 1; i <= N; i++)
if (graph[i].size() == 0)
count++;
return count;
}
int main()
{
int N = 6;
vector<int> graph[7];
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);
}
|
Java
import java.util.*;
class GFG
{
static int compute(int []graph, int N)
{
int count = 0;
for (int i = 1; i < 7; i++)
{
if (graph[i] == 0)
count++;
}
return count;
}
public static void main(String[] args)
{
int N = 6;
int []graph = new int[7];
graph[1] = 2;
graph[2] = 1;
graph[2] = 3;
graph[3] = 2;
graph[5] = 6;
graph[6] = 5;
System.out.println(compute(graph, N));
}
}
|
Python3
def compute(graph, N):
count = 0
for i in range(1, N+1):
if (len(graph[i]) == 0):
count += 1
return count
if __name__ == '__main__':
N = 6
graph = [[] for i in range(7)]
graph[1].append(2)
graph[2].append(1)
graph[2].append(3)
graph[3].append(2)
graph[5].append(6)
graph[6].append(5)
print(compute(graph, N))
|
C#
using System;
class GFG
{
static int compute(int []graph, int N)
{
int count = 0;
for (int i = 1; i < 7; i++)
{
if (graph[i] == 0)
count++;
}
return count;
}
public static void Main(String[] args)
{
int N = 6;
int []graph = new int[7];
graph[1] = 2;
graph[2] = 1;
graph[2] = 3;
graph[3] = 2;
graph[5] = 6;
graph[6] = 5;
Console.WriteLine(compute(graph, N));
}
}
|
Javascript
<script>
function compute(graph,N)
{
let count = 0;
for (let i = 1; i < 7; i++)
{
if (graph[i].length == 0)
count++;
}
return count;
}
let N = 6;
let graph = new Array(7);
for(let i=0;i<7;i++)
{
graph[i]=[];
}
graph[1].push(2)
graph[2].push(1)
graph[2].push(3)
graph[3].push(2)
graph[5].push(6)
graph[6].push(5)
document.write(compute(graph, N));
</script>
|
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.