Color a grid such that all same color cells are connected either horizontally or vertically | Java 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
import java . util . * ; class GFG { static void solve ( List < Integer > arr , int r , int c ) { int idx = 1 ; int [ ] [ ] dp = new int [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { if ( i % 2 == 0 ) { for ( int j = 0 ; j < c ; j ++ ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } else { for ( int j = c - 1 ; j >= 0 ; j -- ) { if ( arr . get ( idx - 1 ) == 0 ) idx ++ ; dp [ i ] [ j ] = idx ; arr . set ( idx - 1 , arr . get ( idx - 1 ) - 1 ) ; } } } for ( int i = 0 ; i < r ; ++ i ) { for ( int j = 0 ; j < c ; ++ j ) { System . out . print ( dp [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int r = 3 , c = 5 ; int n = 5 ; List < Integer > arr = Arrays . asList ( 1 , 2 , 3 , 4 , 5 ) ; solve ( arr , r , c ) ; } }