Graph representations using set and hash |  ; Adds an edge to undirected graph ; Add an edge from source to destination . A new element is inserted to adjacent list of source . ; Add an dge from destination to source . A new element is inserted to adjacent list of destination . ; A utility function to print the adjacency list representation of graph ; Search for a given edge in graph ; Driver code ; Create the graph given in the above figure ; Print adjacenecy list representation of graph ; Search the given edge in a graph
class graph ( object ) : NEW_LINE INDENT def __init__ ( self , v ) : NEW_LINE INDENT self . v = v NEW_LINE self . graph = dict ( ) NEW_LINE DEDENT def addEdge ( self , source , destination ) : NEW_LINE INDENT if source not in self . graph : NEW_LINE INDENT self . graph = { destination } NEW_LINE DEDENT else : NEW_LINE INDENT self . graph . add ( destination ) NEW_LINE DEDENT if destination not in self . graph : NEW_LINE INDENT self . graph [ destination ] = { source } NEW_LINE DEDENT else : NEW_LINE INDENT self . graph [ destination ] . add ( source ) NEW_LINE DEDENT DEDENT def print ( self ) : NEW_LINE INDENT for i , adjlist in sorted ( self . graph . items ( ) ) : NEW_LINE INDENT print ( " Adjacency ▁ list ▁ of ▁ vertex ▁ " , i ) NEW_LINE for j in sorted ( adjlist , reverse = True ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT print ( ' ' ) NEW_LINE DEDENT DEDENT def searchEdge ( self , source , destination ) : NEW_LINE INDENT if source in self . graph : NEW_LINE INDENT if destination in self . graph : NEW_LINE INDENT print ( " Edge from { 0 } to { 1 } found . " . format ( source , destination ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Edge from { 0 } to { 1 } not found . " . format ( source , destination ) ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Source vertex { } is not present in graph . " . format ( source ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT g = graph ( 5 ) NEW_LINE g . addEdge ( 0 , 1 ) NEW_LINE g . addEdge ( 0 , 4 ) NEW_LINE g . addEdge ( 1 , 2 ) NEW_LINE g . addEdge ( 1 , 3 ) NEW_LINE g . addEdge ( 1 , 4 ) NEW_LINE g . addEdge ( 2 , 3 ) NEW_LINE g . addEdge ( 3 , 4 ) NEW_LINE g . print ( ) NEW_LINE g . searchEdge ( 2 , 1 ) NEW_LINE g . searchEdge ( 0 , 3 ) NEW_LINE DEDENT