Smallest element from all square submatrices of size K from a given Matrix

Given a matrix arr[][] and an integer K, the task is to find the smallest element from all possible square submatrices of size K from the given matrix.

Examples:

Input: K = 2, arr[][] ={ {1, 2, 3}, {4, 5, 6},  {7, 8, 9} }
Output: 
1 2 
4 5
Explanation:
Smallest elements from all possible square submatrices of size 2 are as follows:
{ {1, 2}, {4, 5} } -> 1
{ {2, 3}, {5, 6} } -> 2
{ {4, 5}, {7, 8} } -> 4
{ {5, 6}, {8, 9} } -> 5 

Input: K = 3,  
arr[][] = { {-1, 5, 4, 1, -3}, 
{4, 3, 1, 1, 6}, 
{2, -2, 5, 3, 1}, 
{8, 5, 1, 9, -4}, 
{12, 3, 5, 8, 1} }
Output: 
-2 -2 -3
-2 -2 -4
-2 -2 -4

Naive Approach: The simplest approach to solve the problem is to generate all possible square submatrices of size K from the given matrix and print the smallest element from each such submatrices.
Time Complexity: O(N * M * K2)
Auxiliary Space: O(1)

Efficient Approach: Follow the steps below to optimize the above approach:



  • Traverse over each row of the matrix and for every arr[i][j], update in-place the smallest element present between indices arr[i][j] to arr[i][j + K – 1] (0 <= j < M – K + 1).
  • Similarly, traverse over each colum of the matrix and for every arr[i][j], update in-place the smallest element present between indices arr[i][j] to arr[i+K-1][j] (0 <= i < N – K + 1).
  • After performing the above operations, the top-left submatrix of size (N – K + 1)*(M – K + 1) of the matrix arr[][] consists of all the smallest elements of all the K x K sub-matrices of the given matrix.
  • Therefore, print the submatrix of size (N – K + 1)*(M – K + 1) as the required output.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program for
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to returns a smallest
// elements of all KxK submatrices
// of a given NxM matrix
vector<vector<int> > matrixMinimum(
       vector<vector<int> > nums, int K)
{
  // Stores the dimensions
  // of the given matrix
  int N = nums.size();
  int M = nums[0].size();
 
  // Stores the required
  // smallest elements
  vector<vector<int> > res(N - K + 1,
                           vector<int>(M - K + 1));
 
  // Update the smallest elements row-wise
  for (int i = 0; i < N; i++)
  {
    for (int j = 0; j < M - K + 1; j++)
    {
      int mini = INT_MAX;
      for (int k = j; k < j + K; k++)
      {
        mini = min(mini, nums[i][k]);
      }
      nums[i][j] = mini;
    }
  }
 
  // Update the minimum column-wise
  for (int j = 0; j < M; j++)
  {
    for (int i = 0; i < N - K + 1; i++)
    {
      int mini = INT_MAX;
      for (int k = i; k < i + K; k++)
      {
        mini = min(mini, nums[k][j]);
      }
      nums[i][j] = mini;
    }
  }
 
  // Store the final submatrix with
  // required minimum values
  for (int i = 0; i < N - K + 1; i++)
    for (int j = 0; j < M - K + 1; j++)
      res[i][j] = nums[i][j];
 
  // Return the resultant matrix
  return res;
}
 
void smallestinKsubmatrices(vector<vector<int> > arr,
                            int K)
{
  // Function Call
  vector<vector<int> > res = matrixMinimum(arr, K);
 
  // Print resultant matrix with the
  // minimum values of KxK sub-matrix
  for (int i = 0; i < res.size(); i++)
  {
    for (int j = 0; j < res[0].size(); j++)
    {
      cout << res[i][j] << " ";
    }
    cout << endl;
  }
}
 
// Driver Code
int main()
{
 
  // Given matrix
  vector<vector<int> > arr = {{-1, 5, 4, 1, -3},
                              {4, 3, 1, 1, 6},
                              {2, -2, 5, 3, 1},
                              {8, 5, 1, 9, -4},
                              {12, 3, 5, 8, 1}};
 
  // Given K
  int K = 3;
 
  smallestinKsubmatrices(arr, K);
}
 
// This code is contributed by Chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for the above approach
 
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to returns a smallest
    // elements of all KxK submatrices
    // of a given NxM matrix
    public static int[][] matrixMinimum(
        int[][] nums, int K)
    {
        // Stores the dimensions
        // of the given matrix
        int N = nums.length;
        int M = nums[0].length;
 
        // Stores the required
        // smallest elements
        int[][] res
            = new int[N - K + 1][M - K + 1];
 
        // Update the smallest elements row-wise
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M - K + 1; j++) {
 
                int min = Integer.MAX_VALUE;
                for (int k = j; k < j + K; k++) {
                    min = Math.min(min, nums[i][k]);
                }
                nums[i][j] = min;
            }
        }
 
        // Update the minimum column-wise
        for (int j = 0; j < M; j++) {
            for (int i = 0; i < N - K + 1; i++) {
                int min = Integer.MAX_VALUE;
                for (int k = i; k < i + K; k++) {
                    min = Math.min(min, nums[k][j]);
                }
                nums[i][j] = min;
            }
        }
 
        // Store the final submatrix with
        // required minimum values
        for (int i = 0; i < N - K + 1; i++)
            for (int j = 0; j < M - K + 1; j++)
                res[i][j] = nums[i][j];
 
        // Return the resultant matrix
        return res;
    }
 
    public static void smallestinKsubmatrices(
        int arr[][], int K)
    {
        // Function Call
        int[][] res = matrixMinimum(arr, K);
 
        // Print resultant matrix with the
        // minimum values of KxK sub-matrix
        for (int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[0].length; j++) {
                System.out.print(res[i][j] + " ");
            }
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given matrix
        int[][] arr = { { -1, 5, 4, 1, -3 },
                        { 4, 3, 1, 1, 6 },
                        { 2, -2, 5, 3, 1 },
                        { 8, 5, 1, 9, -4 },
                        { 12, 3, 5, 8, 1 } };
 
        // Given K
        int K = 3;
 
        smallestinKsubmatrices(arr, K);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
 
# Function to returns a smallest
# elements of all KxK submatrices
# of a given NxM matrix
def matrixMinimum(nums, K):
 
    # Stores the dimensions
    # of the given matrix
    N = len(nums)
    M = len(nums[0])
 
    # Stores the required
    # smallest elements
    res = [[0 for x in range(M - K + 1)]
              for y in range(N - K + 1)]
 
    # Update the smallest elements row-wise
    for i in range(N):
        for j in range(M - K + 1):
            mn = sys.maxsize
             
            for k in range(j, j + K):
                mn = min(mn, nums[i][k])
 
            nums[i][j] = mn
 
    # Update the minimum column-wise
    for j in range(M):
        for i in range(N - K + 1):
            mn = sys.maxsize
             
            for k in range(i, i + K):
                mn = min(mn, nums[k][j])
 
            nums[i][j] = mn
 
    # Store the final submatrix with
    # required minimum values
    for i in range(N - K + 1):
        for j in range(M - K + 1):
            res[i][j] = nums[i][j]
 
    # Return the resultant matrix
    return res
 
def smallestinKsubmatrices(arr, K):
 
    # Function call
    res = matrixMinimum(arr, K)
 
    # Print resultant matrix with the
    # minimum values of KxK sub-matrix
    for i in range(len(res)):
        for j in range(len(res[0])):
            print(res[i][j], end = " ")
             
        print()
 
# Driver Code
 
# Given matrix
arr = [ [ -1, 5, 4, 1, -3 ],
        [ 4, 3, 1, 1, 6 ],
        [ 2, -2, 5, 3, 1 ],
        [ 8, 5, 1, 9, -4 ],
        [ 12, 3, 5, 8, 1 ] ]
 
# Given K
K = 3
 
# Function call
smallestinKsubmatrices(arr, K)
 
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
 
class GFG{
 
// Function to returns a smallest
// elements of all KxK submatrices
// of a given NxM matrix
public static int[,] matrixMinimum(int[,] nums,
                                   int K)
{
     
    // Stores the dimensions
    // of the given matrix
    int N = nums.GetLength(0);
    int M = nums.GetLength(1);
 
    // Stores the required
    // smallest elements
    int[,] res = new int[N - K + 1,
                         M - K + 1];
 
    // Update the smallest elements row-wise
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < M - K + 1; j++)
        {
            int min = int.MaxValue;
            for(int k = j; k < j + K; k++)
            {
                min = Math.Min(min, nums[i, k]);
            }
            nums[i, j] = min;
        }
    }
 
    // Update the minimum column-wise
    for(int j = 0; j < M; j++)
    {
        for(int i = 0; i < N - K + 1; i++)
        {
            int min = int.MaxValue;
            for(int k = i; k < i + K; k++)
            {
                min = Math.Min(min, nums[k, j]);
            }
            nums[i, j] = min;
        }
    }
 
    // Store the readonly submatrix with
    // required minimum values
    for(int i = 0; i < N - K + 1; i++)
        for(int j = 0; j < M - K + 1; j++)
            res[i, j] = nums[i, j];
 
    // Return the resultant matrix
    return res;
}
 
public static void smallestinKsubmatrices(int [,]arr,
                                          int K)
{
     
    // Function call
    int[,] res = matrixMinimum(arr, K);
 
    // Print resultant matrix with the
    // minimum values of KxK sub-matrix
    for(int i = 0; i < res.GetLength(0); i++)
    {
        for(int j = 0; j < res.GetLength(1); j++)
        {
            Console.Write(res[i, j] + " ");
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main(String[] args)
{
 
    // Given matrix
    int[,] arr = { { -1, 5, 4, 1, -3 },
                   { 4, 3, 1, 1, 6 },
                   { 2, -2, 5, 3, 1 },
                   { 8, 5, 1, 9, -4 },
                   { 12, 3, 5, 8, 1 } };
 
    // Given K
    int K = 3;
 
    smallestinKsubmatrices(arr, K);
}
}
 
// This code is contributed by Amit Katiyar

chevron_right


Output: 

-2 -2 -3 
-2 -2 -4 
-2 -2 -4



Time Complexity: O( max(N, M)3 )
Auxiliary Space: O( (N-K+1)*(M-K+1) ) 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.