Given N rows and M columns of a matrix, the task is to fill the matrix cells using first K integers such that:
- Each group of cells is denoted by a single integer.
- The difference between the group containing the maximum and the minimum number of cells should be minimum.
- All the cells of the same group should be contiguous i.e., for any group, two adjacent cells should follow the rule |xi+1 – xi| + |yi+1 – yi| = 1.
Examples:
Input: N = 5, M = 5, K = 6
Output:
1 1 1 1 1
3 2 2 2 2
3 3 3 4 4
5 5 5 4 4
5 6 6 6 6
Explanation:
The above matrix follows all the conditions above and dividing the matrix into K different groups.Input: N = 2, M = 3, K = 3
Output:
1 1 2
3 3 2
Explanation:
For making three group of the matrix each should have the group of size two.
So, to reduce the difference between the group containing maximum and minimum no of cells and all the matrix cells are used to make the K different groups having all the adjacent elements of the same group follow the |xi + 1 – xi| + |yi + 1 – yi| = 1 as well.
Approach: Below are the steps:
- Create the matrix of size N * M.
- To reduce the difference between group containing max and min no of cells, fill all the part with at least (N*M)/ K cells.
- The remaining part will contain (N * M)/ K + 1 no of cells.
- To follow the given rules, traverse the matrix and fill the matrix with the different parts accordingly.
- Print the matrix after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Function to fill the matrix with // the given conditions void fillMatrix( int ** mat, int & row, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int & col, int sizeOfpart, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int noOfPart, int & start, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int m, int & flag) { Â
    // Count of parts with size sizeOfPart     for ( int i = 0; i < noOfPart; ++i) { Â
        int count = 0; Â
        while (count < sizeOfpart) { Â
            // Assigning the cell             // with no of groups             mat[row][col] = start; Â
            // Update row             if (col == m - 1                 && flag == 1) {                 row++;                 col = m;                 flag = 0;             }             else if (col == 0                      && flag == 0) {                 row++;                 col = -1;                 flag = 1;             } Â
            // Update col             if (flag == 1) {                 col++;             }             else {                 col--;             } Â
            // Increment count             count++;         } Â
        // For new group increment start         start++;     } } Â
// Function to return the reference of // the matrix to be filled int ** findMatrix( int N, int M, int k) { Â
    // Create matrix of size N*M     int ** mat = ( int **) malloc (         N * sizeof ( int *)); Â
    for ( int i = 0; i < N; ++i) {         mat[i] = ( int *) malloc (             M * sizeof ( int ));     } Â
    // Starting index of the matrix     int row = 0, col = 0; Â
    // Size of one group     int size = (N * M) / k;     int rem = (N * M) % k; Â
    // Element to assigned to matrix     int start = 1, flag = 1; Â
    // Fill the matrix that have rem     // no of parts with size size + 1     fillMatrix(mat, row, col, size + 1,                rem, start, M, flag); Â
    // Fill the remaining number of parts     // with each part size is 'size'     fillMatrix(mat, row, col, size,                k - rem, start, M, flag); Â
    // Return the matrix     return mat; } Â
// Function to print the matrix void printMatrix( int ** mat, int N,                  int M) {     // Traverse the rows     for ( int i = 0; i < N; ++i) { Â
        // Traverse the columns         for ( int j = 0; j < M; ++j) {             cout << mat[i][j] << " " ;         }         cout << endl;     } } Â
// Driver Code int main() { Â Â Â Â // Given N, M, K Â Â Â Â int N = 5, M = 5, K = 6; Â
    // Function Call     int ** mat = findMatrix(N, M, K); Â
    // Function Call to print matrix     printMatrix(mat, N, M); Â
    return 0; } |
Java
// Java program for the above approach import java.util.*; Â
class GFG{ Â Â Â Â Â static int N, M; static int [][]mat; static int row, col, start, flag; Â
// Function to fill the matrix with // the given conditions static void fillMatrix( int sizeOfpart,                        int noOfPart,                        int m) {          // Count of parts with size sizeOfPart     for ( int i = 0 ; i < noOfPart; ++i)     {         int count = 0 ; Â
        while (count < sizeOfpart)         {                          // Assigning the cell             // with no of groups             mat[row][col] = start; Â
            // Update row             if (col == m - 1 && flag == 1 )             {                 row++;                 col = m;                 flag = 0 ;             }             else if (col == 0 && flag == 0 )             {                 row++;                 col = - 1 ;                 flag = 1 ;             } Â
            // Update col             if (flag == 1 )             {                 col++;             }             else             {                 col--;             } Â
            // Increment count             count++;         } Â
        // For new group increment start         start++;     } } Â
// Function to return the reference of // the matrix to be filled static void findMatrix( int k) { Â Â Â Â Â Â Â Â Â // Create matrix of size N*M Â Â Â Â mat = new int [M][N]; Â
    // Starting index of the matrix     row = 0 ;     col = 0 ; Â
    // Size of one group     int size = (N * M) / k;     int rem = (N * M) % k; Â
    // Element to assigned to matrix     start = 1 ;     flag = 1 ; Â
    // Fill the matrix that have rem     // no of parts with size size + 1     fillMatrix(size + 1 , rem, M); Â
    // Fill the remaining number of parts     // with each part size is 'size'     fillMatrix(size, k - rem, M); } Â
// Function to print the matrix static void printMatrix() {          // Traverse the rows     for ( int i = 0 ; i < N; ++i)     {                  // Traverse the columns         for ( int j = 0 ; j < M; ++j)         {             System.out.print(mat[i][j] + " " );         }         System.out.println();     } } Â
// Driver Code public static void main(String[] args) { Â Â Â Â Â Â Â Â Â // Given N, M, K Â Â Â Â N = 5 ; Â Â Â Â M = 5 ; Â Â Â Â int K = 6 ; Â
    // Function Call     findMatrix(K); Â
    // Function Call to print matrix     printMatrix(); } } Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approach Â
# Function to fill the matrix with # the given conditions def fillMatrix( sizeOfpart,noOfPart, m):          global start, flag, size, rem, row, col, mat          # Count of parts with size sizeOfPart     for i in range (noOfPart):         count = 0 ; Â
        while (count < sizeOfpart):                      # Assigning the cell             # with no of groups             mat[row][col] = start; Â
            # Update row             if (col = = m - 1 and flag = = 1 ) :                              row + = 1 ;                 col = m;                 flag = 0 ;                          elif (col = = 0 and flag = = 0 ):                              row + = 1 ;                 col = - 1 ;                 flag = 1 ;                          # Update col             if (flag = = 1 ):                    col + = 1 ;             else :                 col - = 1 ;                          # Increment count             count + = 1 ;                  # For new group increment start         start + = 1 ;      # Function to return the reference of # the matrix to be filled def findMatrix(k):          global start, flag, size, rem, row, col, mat          # Create matrix of size N*M     mat = [ [ 0 ] * N for _ in range (M) ]               # Starting index of the matrix     row = 0 ;     col = 0 ; Â
    # Size of one group     size = int ((N * M) / k);     rem = (N * M) % k; Â
    # Element to assigned to matrix     start = 1 ;     flag = 1 ; Â
    # Fill the matrix that have rem     # no of parts with size size + 1     fillMatrix(size + 1 , rem, M); Â
    # Fill the remaining number of parts     # with each part size is 'size'     fillMatrix(size, k - rem, M); Â
# Function to print matrix def printMatrix(): Â Â Â Â Â Â Â Â Â for row in mat: Â Â Â Â Â Â Â Â print ( * row) Â Â Â Â Â # Driver Code Â
# Given N, M, K N = 5 ; M = 5 ; K = 6 ; Â
# Function Call findMatrix(K); Â
# Function Call to prmatrix printMatrix(); Â
# This code is contributed by phasing17 |
C#
// C# program for the // above approach using System; class GFG{ Â Â Â Â Â static int N, M; static int [,]mat; static int row, col, Â Â Â Â Â Â Â Â Â Â Â start, flag; Â
// Function to fill the // matrix with the given // conditions static void fillMatrix( int sizeOfpart,                        int noOfPart,                        int m) {     // Count of parts with size   // sizeOfPart   for ( int i = 0;           i < noOfPart; ++i)   {     int count = 0; Â
    while (count < sizeOfpart)     {       // Assigning the cell       // with no of groups       mat[row, col] = start; Â
      // Update row       if (col == m - 1 &&           flag == 1)       {         row++;         col = m;         flag = 0;       }       else if (col == 0 &&                flag == 0)       {         row++;         col = -1;         flag = 1;       } Â
      // Update col       if (flag == 1)       {         col++;       }       else       {         col--;       } Â
      // Increment count       count++;     } Â
    // For new group increment     // start     start++;   } } Â
// Function to return the // reference of the matrix // to be filled static void findMatrix( int k) {     // Create matrix of   // size N*M   mat = new int [M, N]; Â
  // Starting index of the   // matrix   row = 0;   col = 0; Â
  // Size of one group   int size = (N * M) / k;   int rem = (N * M) % k; Â
  // Element to assigned to   // matrix   start = 1;   flag = 1; Â
  // Fill the matrix that have   // rem no of parts with size   // size + 1   fillMatrix(size + 1,              rem, M); Â
  // Fill the remaining number   // of parts with each part   // size is 'size'   fillMatrix(size, k - rem, M); } Â
// Function to print the // matrix static void printMatrix() {     // Traverse the rows   for ( int i = 0; i < N; ++i)   {     // Traverse the columns     for ( int j = 0; j < M; ++j)     {       Console.Write(mat[i, j] +                     " " );     }     Console.WriteLine();   } } Â
// Driver Code public static void Main(String[] args) {Â Â Â Â Â // Given N, M, K Â Â N = 5; Â Â M = 5; Â Â int K = 6; Â
  // Function Call   findMatrix(K); Â
  // Function Call to   // print matrix   printMatrix(); } } Â
// This code is contributed by 29AjayKumar |
Javascript
// JS program for the above approach let N, M; let mat; let row, col, start, flag; Â
// Function to fill the matrix with // the given conditions function fillMatrix( sizeOfpart,                         noOfPart,                         m) {          // Count of parts with size sizeOfPart     for (let i = 0; i < noOfPart; ++i)     {         let count = 0; Â
        while (count < sizeOfpart)         { Â
            // Assigning the cell             // with no of groups             mat[row][col] = start; Â
            // Update row             if (col == m - 1 && flag == 1)             {                 row++;                 col = m;                 flag = 0;             }             else if (col == 0 && flag == 0)             {                 row++;                 col = -1;                 flag = 1;             } Â
            // Update col             if (flag == 1)             {                 col++;             }             else             {                 col--;             } Â
            // Increment count             count++;         } Â
        // For new group increment start         start++;     } } Â
// Function to return the reference of // the matrix to be filled function findMatrix(k) { Â Â Â Â // Create matrix of size N*M Â Â Â Â mat = new Array(M); Â Â Â Â for ( var i = 0; i < M; i++) Â Â Â Â Â Â Â Â mat[i] = new Array(N).fill(0); Â Â Â Â Â Â
    // Starting index of the matrix     row = 0;     col = 0; Â
    // Size of one group     let size = Math.floor((N * M) / k);     let rem = (N * M) % k; Â
    // Element to assigned to matrix     start = 1;     flag = 1; Â
    // Fill the matrix that have rem     // no of parts with size size + 1     fillMatrix(size + 1, rem, M); Â
    // Fill the remaining number of parts     // with each part size is 'size'     fillMatrix(size, k - rem, M); } Â
// Function to print the matrix function printMatrix() {          // Traverse the rows     for (let i = 0; i < N; ++i)     {                  // Traverse the columns         for (let j = 0; j < M; ++j)         {             process.stdout.write(mat[i][j] + " " );         }         console.log();     } } Â
// Driver Code Â
         // Given N, M, K     N = 5;     M = 5;     let K = 6; Â
Â
    // Function Call     findMatrix(K); Â
    // Function Call to print matrix     printMatrix(); Â
Â
Â
// This code is contributed by phasing17 |
1 1 1 1 1 3 2 2 2 2 3 3 3 4 4 5 5 5 4 4 5 6 6 6 6
Â
Time Complexity: O(N * M)
Auxiliary Space: O(N * M)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!