Count number of edges in an undirected graph

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

```

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 c++ implementation of above idea

```// 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 ;
public :
Graph( int V )
{
this->V = V ;
}
void addEdge ( int u, int v ) ;
int countEdges () ;
};

void Graph :: addEdge ( int u, int v )
{
}

// Returns count of edge in undirected graph
int Graph :: countEdges()
{
int sum = 0;

//traverse all vertex
for (int i = 0 ; i < V ; i++)

// current vertex

// 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 uhown graph

cout << g.countEdges() << endl;

return 0;
}
```

Output:

```14
```

Time Complexity : O(V)

This article is contributed by Nishant Singh. 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.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1 Average Difficulty : 1/5.0
Based on 2 vote(s)