Count number of edges in an undirected graph
Last Updated :
06 Feb, 2023
Given an adjacency list representation undirected graph. Write a function to count the number of edges in the undirected graph. Expected time complexity : O(V) Examples:
Input : Adjacency list representation of
below graph.
Output : 9
Idea is based on Handshaking Lemma. Handshaking lemma is about undirected graph. In every finite undirected graph number of vertices with odd degree is always even. The handshaking lemma is a consequence of the degree sum formula (also sometimes called the handshaking lemma)
So we traverse all vertices, compute sum of sizes of their adjacency lists, and finally returns sum/2. Below implementation of above idea
C++
// C++ program to count number of edge in
// undirected graph
#include<bits/stdc++.h>
using namespace std;
// Adjacency list representation of graph
class Graph
{
int V ;
list < int > *adj;
public :
Graph( int V )
{
this->V = V ;
adj = new list<int>[V];
}
void addEdge ( int u, int v ) ;
int countEdges () ;
};
// add edge to graph
void Graph :: addEdge ( int u, int v )
{
adj[u].push_back(v);
adj[v].push_back(u);
}
// Returns count of edge in undirected graph
int Graph :: countEdges()
{
int sum = 0;
//traverse all vertex
for (int i = 0 ; i < V ; i++)
// add all edge that are linked to the
// current vertex
sum += adj[i].size();
// The count of edge is always even because in
// undirected graph every edge is connected
// twice between two vertices
return sum/2;
}
// driver program to check above function
int main()
{
int V = 9 ;
Graph g(V);
// making above shown graph
g.addEdge(0, 1 );
g.addEdge(0, 7 );
g.addEdge(1, 2 );
g.addEdge(1, 7 );
g.addEdge(2, 3 );
g.addEdge(2, 8 );
g.addEdge(2, 5 );
g.addEdge(3, 4 );
g.addEdge(3, 5 );
g.addEdge(4, 5 );
g.addEdge(5, 6 );
g.addEdge(6, 7 );
g.addEdge(6, 8 );
g.addEdge(7, 8 );
cout << g.countEdges() << endl;
return 0;
}
Java
// Java program to count number of edge in
// undirected graph
import java.io.*;
import java.util.*;
// Adjacency list representation of graph
class Graph
{
int V;
Vector<Integer>[] adj;
//@SuppressWarnings("unchecked")
Graph(int V)
{
this.V = V;
this.adj = new Vector[V];
for (int i = 0; i < V; i++)
adj[i] = new Vector<Integer>();
}
// add edge to graph
void addEdge(int u, int v)
{
adj[u].add(v);
adj[v].add(u);
}
// Returns count of edge in undirected graph
int countEdges()
{
int sum = 0;
// traverse all vertex
for (int i = 0; i < V; i++)
// add all edge that are linked to the
// current vertex
sum += adj[i].size();
// The count of edge is always even because in
// undirected graph every edge is connected
// twice between two vertices
return sum / 2;
}
}
class GFG
{
// Driver Code
public static void main(String[] args) throws IOException
{
int V = 9;
Graph g = new Graph(V);
// making above shown graph
g.addEdge(0, 1);
g.addEdge(0, 7);
g.addEdge(1, 2);
g.addEdge(1, 7);
g.addEdge(2, 3);
g.addEdge(2, 8);
g.addEdge(2, 5);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.addEdge(5, 6);
g.addEdge(6, 7);
g.addEdge(6, 8);
g.addEdge(7, 8);
System.out.println(g.countEdges());
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python3 program to count number of
# edge in undirected graph
# Adjacency list representation of graph
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
# add edge to graph
def addEdge (self, u, v ):
self.adj[u].append(v)
self.adj[v].append(u)
# Returns count of edge in undirected graph
def countEdges(self):
Sum = 0
# traverse all vertex
for i in range(self.V):
# add all edge that are linked
# to the current vertex
Sum += len(self.adj[i])
# The count of edge is always even
# because in undirected graph every edge
# is connected twice between two vertices
return Sum // 2
# Driver Code
if __name__ == '__main__':
V = 9
g = Graph(V)
# making above shown graph
g.addEdge(0, 1 )
g.addEdge(0, 7 )
g.addEdge(1, 2 )
g.addEdge(1, 7 )
g.addEdge(2, 3 )
g.addEdge(2, 8 )
g.addEdge(2, 5 )
g.addEdge(3, 4 )
g.addEdge(3, 5 )
g.addEdge(4, 5 )
g.addEdge(5, 6 )
g.addEdge(6, 7 )
g.addEdge(6, 8 )
g.addEdge(7, 8 )
print(g.countEdges())
# This code is contributed by PranchalK
C#
// C# program to count number of edge in
// undirected graph
using System;
using System.Collections.Generic;
// Adjacency list representation of graph
class Graph
{
public int V;
public List<int>[] adj;
public Graph(int V)
{
this.V = V;
this.adj = new List<int>[V];
for (int i = 0; i < V; i++)
adj[i] = new List<int>();
}
// add edge to graph
public void addEdge(int u, int v)
{
adj[u].Add(v);
adj[v].Add(u);
}
// Returns count of edge in undirected graph
public int countEdges()
{
int sum = 0;
// traverse all vertex
for (int i = 0; i < V; i++)
// add all edge that are linked to the
// current vertex
sum += adj[i].Count;
// The count of edge is always even because in
// undirected graph every edge is connected
// twice between two vertices
return sum / 2;
}
}
class GFG
{
// Driver Code
public static void Main(String[] args)
{
int V = 9;
Graph g = new Graph(V);
// making above shown graph
g.addEdge(0, 1);
g.addEdge(0, 7);
g.addEdge(1, 2);
g.addEdge(1, 7);
g.addEdge(2, 3);
g.addEdge(2, 8);
g.addEdge(2, 5);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.addEdge(5, 6);
g.addEdge(6, 7);
g.addEdge(6, 8);
g.addEdge(7, 8);
Console.WriteLine(g.countEdges());
}
}
// This code is contributed by PrinciRaj1992
JavaScript
class Graph {
constructor(V) {
this.V = V;
this.adj = new Array(V);
for (let i = 0; i < V; i++) {
this.adj[i] = [];
}
}
addEdge(u, v) {
this.adj[u].push(v);
this.adj[v].push(u);
}
countEdges() {
let sum = 0;
for (let i = 0; i < this.V; i++) {
sum += this.adj[i].length;
}
return sum / 2;
}
}
function main() {
let V = 9;
let g = new Graph(V);
g.addEdge(0, 1);
g.addEdge(0, 7);
g.addEdge(1, 2);
g.addEdge(1, 7);
g.addEdge(2, 3);
g.addEdge(2, 8);
g.addEdge(2, 5);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.addEdge(5, 6);
g.addEdge(6, 7);
g.addEdge(6, 8);
g.addEdge(7, 8);
console.log(g.countEdges());
}
main();
// this code is contributed by devendra
Output:
14
Time Complexity: O(V)
Similar Reads
Number of Triangles in Directed and Undirected Graphs Given a Graph, count number of triangles in it. The graph is can be directed or undirected. Example: Input: digraph[V][V] = { {0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 0}, {0, 0, 1, 0} }; Output: 2 Give adjacency matrix represents following directed graph. We have discussed a method based on graph trace
10 min read
Cycles of length n in an undirected and connected graph Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
10 min read
Count number of trees in a forest Given n nodes of a forest (collection of trees), find the number of trees in the forest. Examples : Input : edges[] = {0, 1}, {0, 2}, {3, 4} Output : 2 Explanation : There are 2 trees 0 3 / \ \ 1 2 4 Approach : Apply DFS on every node. Increment count by one if every connected node is visited from o
15 min read
Find the Number of Cliques in a Graph In graph theory, a clique is a subset of vertices of an undirected graph such that every two distinct vertices in the clique are adjacent, that is, they are connected by an edge of the graph. The number of cliques in a graph is the total number of cliques that can be found in the graph. The Mathemat
15 min read
Count of nodes with maximum connection in an undirected graph Given an undirected graph with N nodes and E edges, followed by E edge connections. The task is to find the count of nodes with maximum connections Examples: Input: N =10, E =13, edges[][] = { {1, 4}, {2, 3}, {4, 5}, {3, 9}, {6, 9}, {3, 8}, {10, 4}, {2, 7}, {3, 6}, {2, 8}, {9, 2}, {1, 10}, {9, 10} }
6 min read