Count number of edges in an 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
class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V NEW_LINE self . adj = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addEdge ( self , u , v ) : NEW_LINE INDENT self . adj [ u ] . append ( v ) NEW_LINE self . adj [ v ] . append ( u ) NEW_LINE DEDENT def countEdges ( self ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( self . V ) : NEW_LINE INDENT Sum += len ( self . adj [ i ] ) NEW_LINE DEDENT return Sum // 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 9 NEW_LINE g = Graph ( V ) NEW_LINE g . addEdge ( 0 , 1 ) NEW_LINE g . addEdge ( 0 , 7 ) NEW_LINE g . addEdge ( 1 , 2 ) NEW_LINE g . addEdge ( 1 , 7 ) NEW_LINE g . addEdge ( 2 , 3 ) NEW_LINE g . addEdge ( 2 , 8 ) NEW_LINE g . addEdge ( 2 , 5 ) NEW_LINE g . addEdge ( 3 , 4 ) NEW_LINE g . addEdge ( 3 , 5 ) NEW_LINE g . addEdge ( 4 , 5 ) NEW_LINE g . addEdge ( 5 , 6 ) NEW_LINE g . addEdge ( 6 , 7 ) NEW_LINE g . addEdge ( 6 , 8 ) NEW_LINE g . addEdge ( 7 , 8 ) NEW_LINE print ( g . countEdges ( ) ) NEW_LINE DEDENT