Check whether a given graph is Bipartite or not | Python3 program to find out whether a given graph is Bipartite or not using recursion . ; color this pos as c and all its neighbours and 1 - c ; start is vertex 0 ; two colors 1 and 0 ; Driver Code
V = 4 NEW_LINE def colorGraph ( G , color , pos , c ) : NEW_LINE INDENT if color [ pos ] != - 1 and color [ pos ] != c : NEW_LINE INDENT return False NEW_LINE DEDENT color [ pos ] = c NEW_LINE ans = True NEW_LINE for i in range ( 0 , V ) : NEW_LINE INDENT if G [ pos ] [ i ] : NEW_LINE INDENT if color [ i ] == - 1 : NEW_LINE INDENT ans &= colorGraph ( G , color , i , 1 - c ) NEW_LINE DEDENT if color [ i ] != - 1 and color [ i ] != 1 - c : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if not ans : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isBipartite ( G ) : NEW_LINE INDENT color = [ - 1 ] * V NEW_LINE pos = 0 NEW_LINE return colorGraph ( G , color , pos , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT G = [ [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] ] NEW_LINE if isBipartite ( G ) : print ( " Yes " ) NEW_LINE else : print ( " No " ) NEW_LINE DEDENT