Open In App

Minimum number of integers required to fill the NxM grid

Improve
Improve
Like Article
Like
Save
Share
Report

Given a grid of size (NxM) is to be filled with integers. Filling of cells in the grid should be done in the following manner:

  1. let A, B and C are three cell and, B and C shared a side with A.
  2. Value of cell B and C must be distinct.
  3. Let L be the number of distinct integers in a grid.
  4. Each cell should contain value from 1 to L.

The task is to find the minimum value of L and any resulting grid. Examples:

Input: N = 1, M = 2
Output:
L = 2
grid = {1, 2}

Input: 2 3
Output:
L = 3
grid = {{1, 2, 3},
        {1, 2, 3}}
Explanation: Integers in the neighbors 
of cell (2, 2) are 1, 2 and 3.
All numbers are pairwise distinct.

Approach: It is given that two cells shared a side with another cell must be distinct. For each such cell, there will be a possible maximum of 8 cells in a grid from whom its value must be different. It will follow the 4 colour problem: Maximum colour required to fill the regions will be 4.

  1. For N<4 or M<4 Number of integers required may vary from 1 to 4. Checking 8 cells and then fill the current cell. If number of distinct integers in 8 cells is less than L then fill the current cell with any remaining integer, otherwise fill the current cells with L+1 integer.
  2. For N>=4 and M>=4 Number of integers required must be 4 according to 4 colour problem. Use the 4×4 matrix to fill the NxM matrix.
1 2 3 4
1 2 3 4
3 4 1 2
3 4 1 2

Below is the implementation of the above approach: Implementation: 

C++




// C++ implementation of
/// above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to display the matrix
void display_matrix(vector<vector<int>> &A)
{
  for (auto x: A){
    for(auto y: x){
      cout << y << " ";
    }
    cout << endl;
  }
}
 
// Function for calculation
vector<vector<int>> cal_main(vector<vector<int>> &A,
                             int L,set<int>& x,int i,
                             int j, int N, int M)
{
  set<int> s;
 
  // Checking 8 cells and
  // then fill the current cell.
  if ((i - 2) >= 0)
    s.insert(A[i - 2][j]);
  if ((i + 2) < N)
    s.insert(A[i + 2][j]);
  if ((j - 2) >= 0)
    s.insert(A[i][j - 2]);
  if ((j + 2) < M)
    s.insert(A[i][j + 2]);
  if ((i - 1) >= 0 && (j - 1) >= 0)
    s.insert(A[i - 1][j - 1]);
  if ((i - 1) >= 0 && (j + 1) < M)
    s.insert(A[i - 1][j + 1]);
  if ((i + 1) < N && (j - 1) >= 0)
    s.insert(A[i + 1][j - 1]);
  if ((i + 1) < N && (j + 1) < M)
    s.insert(A[i + 1][j + 1]);
 
  // Set to contain distinct value
  // of integers in 8 cells.
  auto it = s.find(0);
  if (it != s.end())
    s.erase(it);
 
  if (s.size() < L)
  {
    set<int> w;
 
    // Set contain remaining integers
    for(auto i: x)
    {
      if (!s.count(i))
        w.insert(i);
    }
 
    // fill the current cell
    // with maximum remaining integer
    A[i][j] = *w.begin();
  }
  else
  {
    // fill the current cells with L + 1 integer.
    A[i][j] = L + 1;
    L += 1;
 
    // Increase the value of L
    x.insert(L);
  }
  return A;
}
 
 
// Function to find the number
// of distinct integers
void solve(int N,int M)
{
  // initialise the list (NxM) with 0.
  vector<vector<int>> A(N, vector<int> (M, 0));
 
  // Set to contain distinct
  // value of integers from 1-L
  set<int> x;
  int L = 0;
 
  // Number of integer required
  // may vary from 1 to 4.
  if (N < 4 || M < 4)
  {
    if (N > M) // if N is greater
      for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
          A = cal_main(A, L, x, i, j, N, M);
 
    else
    {
      // if M is greater
      for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
          A = cal_main(A, L, x, i, j, N, M);
    }
  }
  else
  {
    // Number of integer required
    // must be 4
    L = 4;
 
    // 4×4 matrix to fill the NxM matrix.
    vector<vector<int>> m4 = {{1, 2, 3, 4},
                              {1, 2, 3, 4},
                              {3, 4, 1, 2},
                              {3, 4, 1, 2}};
 
    for (int i = 0; i < 4; i++)
      for (int j = 0; j < 4; j++)
        A[i][j] = m4[i][j];
    for (int i = 4; i < N; i++)
      for (int j = 0; j < 4; j++)
        A[i][j] = m4[i % 4][j];
    for (int j = 4; j < M; j++) 
      for (int i = 0; i < N; i++)
        A[i][j] = A[i][j % 4];
  }
  cout << L << endl;
  display_matrix(A);
}
 
// Driver Code
 
// sample input
// Number of rows and columns
int main(){
 
  int N = 10;
  int M = 5;
  solve(N, M);
  return 0;
 
}
 
// This code is contributed by Nighi goel.


Java




// java implementation of
/// above approach
import java.io.*;
import java.util.HashSet;
import java.util.*;
// "static void main" must be defined in a public class.
public class Main {
     
 
    // Function to display the matrix
    static void display_matrix(int[][] A, int n, int m)
    {
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                System.out.print(A[i][j] + " ");
            }
            System.out.println();
        }
    }
 
     
    // Function for calculation
    static void cal_main(int[][] A, int L,HashSet<Integer> x,int i, int j, int N, int M)
    {
      HashSet<Integer> s = new HashSet<Integer> ();
 
      // Checking 8 cells and
      // then fill the current cell.
      if ((i - 2) >= 0)
        s.add(A[i - 2][j]);
      if ((i + 2) < N)
        s.add(A[i + 2][j]);
      if ((j - 2) >= 0)
        s.add(A[i][j - 2]);
      if ((j + 2) < M)
        s.add(A[i][j + 2]);
      if ((i - 1) >= 0 && (j - 1) >= 0)
        s.add(A[i - 1][j - 1]);
      if ((i - 1) >= 0 && (j + 1) < M)
        s.add(A[i - 1][j + 1]);
      if ((i + 1) < N && (j - 1) >= 0)
        s.add(A[i + 1][j - 1]);
      if ((i + 1) < N && (j + 1) < M)
        s.add(A[i + 1][j + 1]);
 
      // Set to contain distinct value
      // of integers in 8 cells.
      if (s.contains(0))
        s.remove(0);
 
      if (s.size() < L)
      {
        HashSet<Integer> w = new HashSet<Integer> ();
 
        // Set contain remaining integers
         
        for(Integer ele: x)
        {
          if (s.contains(ele) == false)
            w.add(ele);
        }
 
        // fill the current cell
        // with maximum remaining integer
        A[i][j] = Collections.max(w);
      }
      else
      {
        // fill the current cells with L + 1 integer.
        A[i][j] = L + 1;
        L += 1;
 
        // Increase the value of L
        x.add(L);
      }
    }
 
     
    // Function to find the number
    // of distinct integers
    static void solve(int N,int M)
    {
      // initialise the list (NxM) with 0.
      int[][] A = new int[N][M];
      for(int i = 0; i < N; i++){
          for(int j = 0; j < M; j++){
              A[i][j] = 0;
          }
      }
 
      // Set to contain distinct
      // value of integers from 1-L
      HashSet<Integer> x = new  HashSet<Integer>(); 
      int L = 0;
 
      // Number of integer required
      // may vary from 1 to 4.
      if (N < 4 || M < 4)
      {
        if (N > M) // if N is greater
          for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
              cal_main(A, L, x, i, j, N, M);
 
        else
        {
          // if M is greater
          for (int i = 0; i < N; i++)
            for (int j = 0; j < N; j++)
              cal_main(A, L, x, i, j, N, M);
        }
      }
      else
      {
        // Number of integer required
        // must be 4
        L = 4;
 
        // 4×4 matrix to fill the NxM matrix.
        int[][] m4 = {{1, 2, 3, 4},
                                  {1, 2, 3, 4},
                                  {3, 4, 1, 2},
                                  {3, 4, 1, 2}};
 
        for (int i = 0; i < 4; i++)
          for (int j = 0; j < 4; j++)
            A[i][j] = m4[i][j];
        for (int i = 4; i < N; i++)
          for (int j = 0; j < 4; j++)
            A[i][j] = m4[i % 4][j];
        for (int j = 4; j < M; j++) 
          for (int i = 0; i < N; i++)
            A[i][j] = A[i][j % 4];
      }
      System.out.println(L);
      display_matrix(A, N, M);
    }   
 
     
    // Driver Code
 
    // sample input
    // Number of rows and columns
    public static void main(String[] args) {
        int N = 10;
        int M = 5;
        solve(N, M);
    }
}
 
// The code is contributed by Nidhi goel.


Python3




# Python 3 implementation of
# above approach
 
# Function to display the matrix
def display_matrix(A):
    for i in A:
        print(*i)
 
# Function for calculation
def cal_main(A, L, x, i, j):
    s = set()
 
    # Checking 8 cells and
    # then fill the current cell.
    if (i - 2) >= 0:
        s.add(A[i - 2][j])
    if (i + 2) < N:
        s.add(A[i + 2][j])
    if (j - 2) >= 0:
        s.add(A[i][j - 2])
    if (j + 2) < M:
        s.add(A[i][j + 2])
    if (i - 1) >= 0 and (j - 1) >= 0:
        s.add(A[i - 1][j - 1])
    if (i - 1) >= 0 and (j + 1) < M:
        s.add(A[i - 1][j + 1])
    if (i + 1) < N and (j - 1) >= 0:
        s.add(A[i + 1][j - 1])
    if (i + 1) < N and (j + 1) < M:
        s.add(A[i + 1][j + 1])
     
    # Set to contain distinct value
    # of integers in 8 cells.
    s = s.difference({0})
 
    if len(s) < L:
 
        # Set contain remaining integers
        w = x.difference(s)
 
        # fill the current cell
        # with maximum remaining integer
        A[i][j] = max(w)
    else:
 
        # fill the current cells with L + 1 integer.
        A[i][j] = L + 1
        L += 1
 
        # Increase the value of L
        x.add(L)
    return A, L, x
 
 
# Function to find the number
# of distinct integers
def solve(N, M):
 
    # initialise the list (NxM) with 0.
    A = []
    for i in range(N):
        K = []
        for j in range(M):
            K.append(0)
        A.append(K)
     
    # Set to contain distinct
    # value of integers from 1-L
    x = set()
    L = 0
 
    # Number of integer required
    # may vary from 1 to 4.
    if N < 4 or M < 4:
        if N > M: # if N is greater
            for i in range(N):
                for j in range(M):
                    cal_main(A, L, x, i, j)
 
        else:
            # if M is greater
            for j in range(M):
                for i in range(N):
                    cal_main(A, L, x, i, j)
    else:
 
        # Number of integer required
        # must be 4
        L = 4
 
        # 4×4 matrix to fill the NxM matrix.
        m4 = [[1, 2, 3, 4],
            [1, 2, 3, 4],
            [3, 4, 1, 2],
            [3, 4, 1, 2]]
 
        for i in range(4):
            for j in range(4):
                A[i][j] = m4[i][j]
        for i in range(4, N):
            for j in range(4):
                A[i][j] = m4[i % 4][j]
        for j in range(4, M):
            for i in range(N):
                A[i][j] = A[i][j % 4]
    print(L)
    display_matrix(A)
 
 
# Driver Code
if __name__ == "__main__":
 
    # sample input
    # Number of rows and columns
    N, M = 10, 5
    solve(N, M)


C#




using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
// C# implementation of
// above approach
 
class GFG {
 
  // Function to display the matrix
  public static void display_matrix(int[,] A, int N, int M)
  {
    for(int i = 0; i < N; i++){
      for(int j = 0; j < M; j++){
        Console.Write(A[i, j] + " ");
      }
      Console.WriteLine();
    }
 
  }   
 
  // Function for calculation
  public static void cal_main(int[,] A, int L, HashSet<int> x,int i, int j, int N, int M)
  {
    HashSet<int> s = new HashSet<int>();
 
    // Checking 8 cells and
    // then fill the current cell.
    if ((i - 2) >= 0)
      s.Add(A[i - 2,j]);
    if ((i + 2) < N)
      s.Add(A[i + 2,j]);
    if ((j - 2) >= 0)
      s.Add(A[i,j - 2]);
    if ((j + 2) < M)
      s.Add(A[i,j + 2]);
    if ((i - 1) >= 0 && (j - 1) >= 0)
      s.Add(A[i - 1,j - 1]);
    if ((i - 1) >= 0 && (j + 1) < M)
      s.Add(A[i - 1,j + 1]);
    if ((i + 1) < N && (j - 1) >= 0)
      s.Add(A[i + 1,j - 1]);
    if ((i + 1) < N && (j + 1) < M)
      s.Add(A[i + 1,j + 1]);
 
    // Set to contain distinct value
    // of integers in 8 cells.
    if (s.Contains(0))
      s.Remove(0);
 
    if (s.Count < L)
    {
      HashSet<int> w = new HashSet<int>();
 
      // Set contain remaining integers
      foreach (var num in x) {
        if(!x.Contains(num)){
          w.Add(num);
        }
      }
 
      // fill the current cell
      // with maximum remaining integer
      A[i,j] = w.Max();
    }
    else
    {
      // fill the current cells with L + 1 integer.
      A[i,j] = L + 1;
      L += 1;
 
      // Increase the value of L
      x.Add(L);
    }
  }   
 
  // Function to find the number
  // of distinct integers
  public static void solve(int N,int M)
  {
    // initialise the list (NxM) with 0.
    int[,] A = new int[N, M];
    for(int i = 0; i < N; i++){
      for(int j = 0; j < M; j++){
        A[i,j] = 0;
      }
    }
 
    // Set to contain distinct
    // value of integers from 1-L
    HashSet<int> x = new HashSet<int>();
    int L = 0;
 
    // Number of integer required
    // may vary from 1 to 4.
    if (N < 4 || M < 4)
    {
      if (N > M) // if N is greater
        for (int i = 0; i < N; i++)
          for (int j = 0; j < N; j++)
            cal_main(A, L, x, i, j, N, M);
 
      else
      {
        // if M is greater
        for (int i = 0; i < N; i++)
          for (int j = 0; j < N; j++)
            cal_main(A, L, x, i, j, N, M);
      }
    }
    else
    {
      // Number of integer required
      // must be 4
      L = 4;
 
      // 4×4 matrix to fill the NxM matrix.
      int[,] m4 =  {{1, 2, 3, 4},
                    {1, 2, 3, 4},
                    {3, 4, 1, 2},
                    {3, 4, 1, 2}};
 
      for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
          A[i,j] = m4[i,j];
      for (int i = 4; i < N; i++)
        for (int j = 0; j < 4; j++)
          A[i,j] = m4[i % 4,j];
      for (int j = 4; j < M; j++) 
        for (int i = 0; i < N; i++)
          A[i,j] = A[i,j % 4];
    }
    Console.WriteLine(L);
    display_matrix(A, N, M);
  }
 
  static void Main() {
 
    int N = 10;
    int M = 5;
    solve(N, M);
  }
}
 
// The code is contributed by Nidhi goel.


Javascript




// JavaScript implementation of
/// above approach
 
// Function to display the matrix
function display_matrix(A)
{
    for (let i of A)
        console.log(i)
}
 
// Function for calculation
function cal_main(A, L, x, i, j)
{
    let s = new Set()
 
    // Checking 8 cells and
    // then fill the current cell.
    if ((i - 2) >= 0)
        s.add(A[i - 2][j])
    if ((i + 2) < N)
        s.add(A[i + 2][j])
    if ((j - 2) >= 0)
        s.add(A[i][j - 2])
    if ((j + 2) < M)
        s.add(A[i][j + 2])
    if ((i - 1) >= 0 && (j - 1) >= 0)
        s.add(A[i - 1][j - 1])
    if ((i - 1) >= 0 && (j + 1) < M)
        s.add(A[i - 1][j + 1])
    if ((i + 1) < N && (j - 1) >= 0)
        s.add(A[i + 1][j - 1])
    if ((i + 1) < N && (j + 1) < M)
        s.add(A[i + 1][j + 1])
     
    // Set to contain distinct value
    // of integers in 8 cells.
    if (s.has(0))
        s.remove(0)
 
    if (s.length < L)
    {
        let w =new Set()
        // Set contain remaining integers
        for (let i of x)
        {
            if (!s.has(i))
                w.add(i)
        }
 
        // fill the current cell
        // with maximum remaining integer
        A[i][j] = Math.max(w)
    }
    else
    {
        // fill the current cells with L + 1 integer.
        A[i][j] = L + 1
        L += 1
 
        // Increase the value of L
        x.add(L)
    }
    return A
}
 
 
// Function to find the number
// of distinct integers
function solve(N, M)
{
    // initialise the list (NxM) with 0.
    let A = []
    for (var i = 0; i < N; i++)
    {
        let K = []
        for (var j = 0; j < M; j++)
            K.push(0)
        A.push(K)
    }
 
    // Set to contain distinct
    // value of integers from 1-L
    let x = new Set()
    let L = 0
 
    // Number of integer required
    // may vary from 1 to 4.
    if (N < 4 || M < 4)
    {
        if (N > M) // if N is greater
            for (var i = 0; i < N; i++)
                for (var j = 0; j < N; j++)
                    A = cal_main(A, L, x, i, j)
 
        else
        {
            // if M is greater
            for (var i = 0; i < N; i++)
                for (var j = 0; j < N; j++)
                    A = cal_main(A, L, x, i, j)
        }
    }
    else
    {
        // Number of integer required
        // must be 4
        L = 4
 
        // 4×4 matrix to fill the NxM matrix.
        let m4 = [[1, 2, 3, 4],
            [1, 2, 3, 4],
            [3, 4, 1, 2],
            [3, 4, 1, 2]]
 
        for (var i = 0; i < 4; i++)
            for (var j = 0; j < 4; j++)
                A[i][j] = m4[i][j]
        for (var i = 4; i < N; i++)
            for (var j = 0; j < 4; j++)
                A[i][j] = m4[i % 4][j]
        for (var j = 4; j < M; j++) 
            for (var i = 0; i < N; i++)
                A[i][j] = A[i][j % 4]
    }
    console.log(L)
    display_matrix(A)
}
     
// Driver Code
 
// sample input
// Number of rows and columns
let N = 10
let M = 5
solve(N, M)
 
// This code is contributed by phasing17


Output

4
1 2 3 4 1 
1 2 3 4 1 
3 4 1 2 3 
3 4 1 2 3 
1 2 3 4 1 
1 2 3 4 1 
3 4 1 2 3 
3 4 1 2 3 
1 2 3 4 1 
1 2 3 4 1 

Time Complexity: O(N*M)
Auxiliary Space: O(N*M) 



Last Updated : 28 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads