The Wayback Machine - https://web.archive.org/web/20240831210522/https://www.geeksforgeeks.org/count-number-edges-undirected-graph/
Open In App

Count number of edges in an undirected graph

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
34.09%
13.7K

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

What is Undirected Graph? | Undirected Graph meaning
An undirected graph is a type of graph where the edges have no specified direction assigned to the them. Characteristics of an Undirected Graph:Edges in an undirected graph are bidirectional in nature.In an undirected graph, there is no concept of a "parent" or "child" vertex as there is no direction to the edges.An undirected graph may contain loo
2 min read
Minimum number of edges required to be removed from an Undirected Graph to make it acyclic
Given an undirected graph consisting of N nodes containing values from the range [1, N] and M edges in a matrix Edges[][], the task is to determine the minimum number of edges required to be removed such that the resulting graph does not contain any cycle. Examples: Input: N = 3, M = 3, edges[][] = [[1, 2], [2, 3], [3, 1]] Output: 1Explanation:Remo
8 min read
Minimum edges to be removed from given undirected graph to remove any existing path between nodes A and B
Given two integers N and M denoting the number of vertices and edges in the graph and array edges[][] of size M, denoting an edge between edges[i][0] and edges[i][1], the task is to find the minimum edges directly connected with node B that must be removed such that there exist no path between vertex A and B. Examples: Input: N = 4, A = 3, B = 2, e
9 min read
Ways to Remove Edges from a Complete Graph to make Odd Edges
Given a complete graph with N vertices, the task is to count the number of ways to remove edges such that the resulting graph has odd number of edges. Examples: Input: N = 3 Output: 4 The initial graph has 3 edges as it is a complete graph. We can remove edges (1, 2) and (1, 3) or (1, 2) and (2, 3) or (1, 3) and (2, 3) or we do not remove any of th
4 min read
Pendant Vertices, Non-Pendant Vertices, Pendant Edges and Non-Pendant Edges in Graph
Pre-requisites: Handshaking theorem. Pendant Vertices Let G be a graph, A vertex v of G is called a pendant vertex if and only if v has degree 1. In other words, pendant vertices are the vertices that have degree 1, also called pendant vertex. Note: Degree = number of edges connected to a vertex In the case of trees, a pendant vertex is known as a
7 min read
Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
Given a number N which is the number of nodes in a graph, the task is to find the maximum number of edges that N-vertex graph can have such that graph is triangle-free (which means there should not be any three edges A, B, C in the graph such that A is connected to B, B is connected to C and C is connected to A). The graph cannot contain a self-loo
4 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum
Given an array arr[] consisting of values of N vertices of an initially unconnected Graph and an integer M, the task is to connect some vertices of the graph with exactly M edges, forming only one connected component, such that no cycle can be formed and Bitwise AND of the connected vertices is maximum possible. Examples: Input: arr[] = {1, 2, 3, 4
9 min read
Count the number of Prime Cliques in an undirected graph
Given a graph with N nodes and E edges, the task is to count the number of clique having their size as a prime number or prime number of nodes in the given graph. A clique is a complete subgraph of a given graph. Examples: Input: N = 5, edges[] = { {1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 5}, {5, 3} } Output: 8 Explanation: In the given undirected graph
13 min read
Count total ways to reach destination from source in an undirected Graph
Given an undirected graph, a source vertex ‘s’ and a destination vertex ‘d’, the task is to count the total paths from the given ‘s’ to ‘d’. Examples Input: s = 1, d = 4 Output: 2 Explanation: Below are the 2 paths from 1 to 4 1 -&gt; 3 -&gt; 4 1 -&gt; 2 -&gt; 3 -&gt; 4 Input: s = 3, d = 9 Output: 6 Explanation: Below are the 6 paths from 3 to 9 3
12 min read
Count of unique lengths of connected components for an undirected graph using STL
Given an undirected graph, the task is to find the size of each connected component and print the number of unique sizes of connected components As depicted above, the count(size of the connected component) associated with the connected components is 2, 3, and 2. Now, the unique count of the components is 2 and 3. Hence, the expected result is Coun
10 min read
Count of simple cycles in an undirected graph having N vertices
Given an undirected unweighted graph of N vertices in the form of adjacency matrix adj[][], the task is to find the number of simple cycles in it. Input: adj[][] = { { 0, 1, 1, 1 }, { 1, 0, 1, 0 }, { 1, 1, 0, 1 }, { 1, 0, 1, 0 } }Output: 2Explanation: The graph is shown below as: The given graph consists of two simple cycles as shownInput: adj[][]
12 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} }Output: 3Explanation: The connections for each of
6 min read
Count ways to change direction of edges such that graph becomes acyclic
Given a directed and unweighted graph consisting of N vertices and an array arr[] where ith vertex has a directed edge to arr[i]. The task is to find the number of ways to change the direction of edges such that the given graph is acyclic. Examples: Input: N = 3, arr[] = {2, 3, 1} The directed graph form by the given information is: Output: 6 Expla
12 min read
Number of shortest paths in an Undirected Weighted Graph
Given a weighted undirected graph G and an integer S, the task is to print the distances of the shortest paths and the count of the number of the shortest paths for each node from a given vertex, S. Examples: Input: S =1, G = Output: Shortest Paths distances are : 0 1 2 4 5 3 2 1 3 Numbers of the shortest Paths are: 1 1 1 2 3 1 1 1 2 Explanation: T
15 min read
Undirected graph splitting and its application for number pairs
Graphs can be used for seemingly unconnected problems. Say the problem of cards which have numbers on both side and you try to create a continuous sequence of numbers using one side. This problem leads to problems in how to split a graph into connected subsets with cycles and connected subsets without cycles. There are known algorithms to detect if
15+ min read
Number of Triangles in an Undirected Graph
Given an Undirected simple graph, We need to find how many triangles it can have. For example below graph have 2 triangles in it. Let A[][] be the adjacency matrix representation of the graph. If we calculate A3, then the number of triangles in Undirected Graph is equal to trace(A3) / 6. Where trace(A) is the sum of the elements on the main diagona
14 min read
Program to find total number of edges in a Complete Graph
Given N number of vertices of a Graph. The task is to find the total number of edges possible in a complete graph of N vertices.Complete Graph: A Complete Graph is a graph in which every pair of vertices is connected by an edge. Examples: Input : N = 3 Output : Edges = 3 Input : N = 5 Output : Edges = 10 The total number of possible edges in a comp
3 min read
Number of Simple Graph with N Vertices and M Edges
Given two integers N and M, the task is to count the number of simple undirected graphs that can be drawn with N vertices and M edges. A simple graph is a graph that does not contain multiple edges and self-loops. Examples: Input: N = 3, M = 1 Output: 3 The 3 graphs are {1-2, 3}, {2-3, 1}, {1-3, 2}. Input: N = 5, M = 1 Output: 10 Approach: The N ve
6 min read
Minimum number of edges between two vertices of a graph using DFS
Given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). We have already discussed this problem using the BFS approach, here we will use the DFS approach. Examples: Input: For the following given graph, find the minimum number of edges between vertex pair (0,
10 min read
Maximum number of edges in Bipartite graph
Given an integer N which represents the number of Vertices. The Task is to find the maximum number of edges possible in a Bipartite graph of N vertices.Bipartite Graph: A Bipartite graph is one which is having 2 sets of vertices.The set are such that the vertices in the same set will never share an edge between them. Examples: Input: N = 10 Output:
3 min read
Minimum number of Edges to be added to a Graph to satisfy the given condition
Given a graph consisting of N nodes numbered from 0 to N - 1 and M edges in the form of pairs {a, b}, the task is to find the minimum number of edges to be added to the graph such that if there exists a path from any node a to node b, then there should be paths from node a to nodes [ a + 1, a + 2, a + 3, ..., b - 1] as well. Examples: Input: N = 7,
12 min read
Maximum number of edges to be removed to contain exactly K connected components in the Graph
Given an undirected graph G with N nodes, M edges, and an integer K, the task is to find the maximum count of edges that can be removed such that there remains exactly K connected components after the removal of edges. If the graph cannot contain K connect components, print -1. Examples: Input: N = 4, M = 3, K = 2, Edges[][] = {{1, 2}, {2, 3}, {3,
9 min read
Number of ways to reach at starting node after travelling through exactly K edges in a complete graph
Given a complete graph having N nodes and N*(N-1)/2 edges and a positive integer K, the task is to find the number of ways if you are starting at node 1 and end at the same node if exactly K edges have to be traversed. Input: N = 4, K = 3Output: 6Explanation: The possible ways are- 1?2?3?1 1?2?4?1 1?3?2?1 1?3?4?1 1?4?2?1 1?4?3?1 Input: N = 5, K = 3
7 min read
Minimum number of edges to be removed from given Graph such that no path exists between given pairs of vertices
Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn't exist any path for every pair (u, v) in the array arr[]. Examples: Input
8 min read
Maximize number of edges added to convert given Tree into a Bipartite Graph
Given a tree of N nodes, the task is to find the maximum number of edges that can be added to the tree such that it becomes a bipartite graph. Note: Self loop or multiple edges are not allowed but cycles are permitted. Examples: Input: N = 4, Edges = {{1, 2}, {2, 3}, {1, 4}} 1 / \ 2 4 / 3Output: 1Explanation: An edge between nodes 3 and 4 can be ad
13 min read
Minimum number of edges between two vertices of a Graph
You are given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). Examples: Input: For given graph G. Find minimum number of edges between (1, 5). Output: 2Explanation: (1, 2) and (2, 5) are the only edges resulting into shortest path between 1 and 5. The idea
8 min read
Maximum number of edges to be added to a tree so that it stays a Bipartite graph
A tree is always a Bipartite Graph as we can always break into two disjoint sets with alternate levels. In other words we always color it with two colors such that alternate levels have same color. The task is to compute the maximum no. of edges that can be added to the tree so that it remains Bipartite Graph. Examples: Input : Tree edges as vertex
6 min read
Maximum Number of Edges in a Directed Graph
In a directed graph, edges have a direction associated with them meaning they point from the one vertex to another. The maximum number of edges in the directed graph depends on the number of the vertices and type of graph. Without Self-loops and Parallel Edges:In a directed graph without self-loops and parallel edges each vertex can have an edge to
4 min read
Article Tags :
Practice Tags :