Color a grid such that all same color cells are connected either horizontally or vertically | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( vector < int > & arr , int r , int c ) { int idx = 1 ; int dp [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < c ; j ++ ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr [ idx - 1 ] -- ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { cout << dp [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int r = 3 , c = 5 ; int n = 5 ; vector < int > arr = { 1 , 2 , 3 , 4 , 5 } ; solve ( arr , r , c ) ; return 0 ; }