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
using System ; using System . Collections . Generic ; class GFG { static void solve ( List < int > arr , int r , int c ) { int idx = 1 ; int [ , ] dp = new int [ r , c ] ; 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 ] = arr [ idx - 1 ] - 1 ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr [ idx - 1 ] == 0 ) idx ++ ; dp [ i , j ] = idx ; arr [ idx - 1 ] = arr [ idx - 1 ] - 1 ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { Console . Write ( dp [ i , j ] + " ▁ " ) ; } Console . Write ( ' STRNEWLINE ' ) ; } } public static void Main ( string [ ] args ) { int r = 3 , c = 5 ; List < int > arr = new List < int > ( ) ; arr . Add ( 1 ) ; arr . Add ( 2 ) ; arr . Add ( 3 ) ; arr . Add ( 4 ) ; arr . Add ( 5 ) ; solve ( arr , r , c ) ; } }