Count number of edges in an undirected graph | Java program to count number of edge in undirected graph ; Adjacency list representation of graph ; add edge to graph ; Returns count of edge in undirected graph ; traverse all vertex ; add all edge that are linked to the current vertex ; The count of edge is always even because in undirected graph every edge is connected twice between two vertices ; Driver Code ; making above uhown graph
import java . io . * ; import java . util . * ; class Graph { int V ; Vector < Integer > [ ] adj ; Graph ( int V ) { this . V = V ; this . adj = new Vector [ V ] ; for ( int i = 0 ; i < V ; i ++ ) adj [ i ] = new Vector < Integer > ( ) ; } void addEdge ( int u , int v ) { adj [ u ] . add ( v ) ; adj [ v ] . add ( u ) ; } int countEdges ( ) { int sum = 0 ; for ( int i = 0 ; i < V ; i ++ ) sum += adj [ i ] . size ( ) ; return sum / 2 ; } } class GFG { public static void main ( String [ ] args ) throws IOException { int V = 9 ; Graph 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 ) ; System . out . println ( g . countEdges ( ) ) ; } }