Color a grid such that all same color cells are connected either horizontally or vertically | Javascript 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 ; reduce the color count ; traverse from right to left for odd rows ; print the grid ; Driver code
function solve ( arr , r , c ) { var idx = 1 ; var dp = new Array ( r ) ; var i , j ; for ( i = 0 ; i < r ; i ++ ) dp [ i ] = new Array ( c ) ; for ( i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( j = 0 ; j < c ; j ++ ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } else { for ( j = c - 1 ; j >= 0 ; j -- ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } } for ( i = 0 ; i < r ; ++ i ) { for ( j = 0 ; j < c ; ++ j ) { document . write ( dp [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } var r = 3 , c = 5 ; var n = 5 ; var arr = [ 1 , 2 , 3 , 4 , 5 ] ; solve ( arr , r , c ) ;