Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups | C ++ 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 ' ; Return the matrix ; Function to print the matrix ; Traverse the rows ; Traverse the columns ; Driver Code ; Given N , M , K ; Function Call ; Function Call to print matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; void fillMatrix ( int * * mat , int & row , int & col , int sizeOfpart , int noOfPart , int & start , int m , int & flag ) { 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 ++ ; } } int * * findMatrix ( int N , int M , int k ) { int * * mat = ( int * * ) malloc ( N * sizeof ( int * ) ) ; for ( int i = 0 ; i < N ; ++ i ) { mat [ i ] = ( int * ) malloc ( M * sizeof ( int ) ) ; } int row = 0 , col = 0 ; int size = ( N * M ) / k ; int rem = ( N * M ) % k ; int start = 1 , flag = 1 ; fillMatrix ( mat , row , col , size + 1 , rem , start , M , flag ) ; fillMatrix ( mat , row , col , size , k - rem , start , M , flag ) ; return mat ; } void printMatrix ( int * * mat , int N , int M ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int N = 5 , M = 5 , K = 6 ; int * * mat = findMatrix ( N , M , K ) ; printMatrix ( mat , N , M ) ; return 0 ; }