Color a grid such that all same color cells are connected either horizontally or vertically | Python3 program to color a grid such that all same color cells are connected either horizontally or vertically ; Current color ; Final grid ; If even row ; Traverse from left to right ; If color has been exhausted , move to the next color ; Color the grid at this position print ( i , j ) ; Reduce the color count ; Traverse from right to left for odd rows ; Print the grid ; Driver code
def solve ( arr , r , c ) : NEW_LINE INDENT idx = 1 NEW_LINE dp = [ [ 0 for i in range ( c ) ] for i in range ( r ) ] NEW_LINE for i in range ( r ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT if ( arr [ idx - 1 ] == 0 ) : NEW_LINE INDENT idx += 1 NEW_LINE DEDENT dp [ i ] [ j ] = idx NEW_LINE arr [ idx - 1 ] -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for j in range ( c - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ idx - 1 ] == 0 ) : NEW_LINE INDENT idx += 1 NEW_LINE DEDENT dp [ i ] [ j ] = idx NEW_LINE arr [ idx - 1 ] -= 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT print ( dp [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT r = 3 NEW_LINE c = 5 NEW_LINE n = 5 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE solve ( arr , r , c ) NEW_LINE DEDENT