m Coloring Problem | Backtracking | A utility function to prsolution ; check if the colored graph is safe or not ; check for every edge ; This function solves the m Coloring problem using recursion . It returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all vertices . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; if current index reached end ; if coloring is safe ; Prthe solution ; Assign each color from 1 to m ; Recur of the rest vertices ; Driver code ; Create following graph and test whether it is 3 colorable ( 3 ) -- - ( 2 ) | / | | / | | / | ( 0 ) -- - ( 1 ) ; Number of colors ; Initialize all color values as 0. This initialization is needed correct functioning of isSafe ( )
def printSolution ( color ) : NEW_LINE INDENT print ( " Solution ▁ Exists : " " ▁ Following ▁ are ▁ the ▁ assigned ▁ colors ▁ " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT print ( color [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def isSafe ( graph , color ) : NEW_LINE INDENT for i in range ( 4 ) : NEW_LINE INDENT for j in range ( i + 1 , 4 ) : NEW_LINE INDENT if ( graph [ i ] [ j ] and color [ j ] == color [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def graphColoring ( graph , m , i , color ) : NEW_LINE INDENT if ( i == 4 ) : NEW_LINE INDENT if ( isSafe ( graph , color ) ) : NEW_LINE INDENT printSolution ( color ) NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT color [ i ] = j NEW_LINE if ( graphColoring ( graph , m , i + 1 , color ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT color [ i ] = 0 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT graph = [ [ 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] , ] NEW_LINE m = 3 NEW_LINE color = [ 0 for i in range ( 4 ) ] NEW_LINE if ( not graphColoring ( graph , m , 0 , color ) ) : NEW_LINE INDENT print ( " Solution ▁ does ▁ not ▁ exist " ) NEW_LINE DEDENT DEDENT