Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups | Java program for the above approach ; Function to fill the matrix with the given conditions ; Count of parts with size sizeOfPart ; Assigning the cell with no of groups ; Update row ; Update col ; Increment count ; For new group increment start ; Function to return the reference of the matrix to be filled ; Create matrix of size N * M ; Starting index of the matrix ; Size of one group ; Element to assigned to matrix ; Fill the matrix that have rem no of parts with size size + 1 ; Fill the remaining number of parts with each part size is ' size ' ; Function to print the matrix ; Traverse the rows ; Traverse the columns ; Driver Code ; Given N , M , K ; Function Call ; Function Call to print matrix
import java . util . * ; class GFG { static int N , M ; static int [ ] [ ] mat ; static int row , col , start , flag ; static void fillMatrix ( int sizeOfpart , int noOfPart , int m ) { for ( int i = 0 ; i < noOfPart ; ++ i ) { int count = 0 ; while ( count < sizeOfpart ) { mat [ row ] [ col ] = start ; if ( col == m - 1 && flag == 1 ) { row ++ ; col = m ; flag = 0 ; } else if ( col == 0 && flag == 0 ) { row ++ ; col = - 1 ; flag = 1 ; } if ( flag == 1 ) { col ++ ; } else { col -- ; } count ++ ; } start ++ ; } } static void findMatrix ( int k ) { mat = new int [ M ] [ N ] ; row = 0 ; col = 0 ; int size = ( N * M ) / k ; int rem = ( N * M ) % k ; start = 1 ; flag = 1 ; fillMatrix ( size + 1 , rem , M ) ; fillMatrix ( size , k - rem , M ) ; } static void printMatrix ( ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { System . out . print ( mat [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { N = 5 ; M = 5 ; int K = 6 ; findMatrix ( K ) ; printMatrix ( ) ; } }