Find sub-matrix with the given sum

Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S.

Examples:

Input: K = 2, S = 14, mat[][] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }}
Output: Yes
1 2
5 6
is the required 2 x 2 sub-matrix with element sum = 14

Input: K = 1, S = 5, mat[][] = {{1, 2}, {7, 8}}
Output: No

Approach: Dynamic programming can be used to solve this problem,

  • Create an array dp[N + 1][N + 1] where dp[i][j] stores the sum of all the elements with row between 1 to i and column between 1 to j.
  • Once the 2-D matrix is generated, now suppose we wish to find sum of square starting with (i, j) to (i + x, j + x). The required sum will be dp[i + x][j + x] – dp[i][j + x] – dp[i + x][j] + dp[i][j] where,
    1. First term denotes the sum of all the elements present in rows between 1 to i + x and columns between 1 to j + x. This area has our required square.
    2. Second two terms is to remove the area which is outside our required region but inside the region calculated in the first step.
    3. Sum of elements of rows between 1 to i and columns between 1 to j is subtracted twice in the second step, so it is added once.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define N 4
  
// Function to return the sum of the sub-matrix
int getSum(int r1, int r2, int c1, int c2,
           int dp[N + 1][N + 1])
{
    return dp[r2][c2] - dp[r2][c1]
           - dp[r1][c2] + dp[r1][c1];
}
  
// Function that returns true if it is possible
// to find the sub-matrix with required sum
bool sumFound(int K, int S, int grid[N][N])
{
  
    // 2-D array to store the sum of
    // all the sub-matrices
    int dp[N + 1][N + 1];
  
    // Filling of dp[][] array
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1]
                               - dp[i][j] + grid[i][j];
  
    // Checking for each possible sub-matrix of size k X k
    for (int i = 0; i < N; i += K)
        for (int j = 0; j < N; j += K) {
            int sum = getSum(i, i + K, j, j + K, dp);
  
            if (sum == S)
                return true;
        }
  
    // Sub-matrix with the given sum not found
    return false;
}
  
// Driver code
int main()
{
    int grid[N][N] = { { 1, 2, 3, 4 },
                       { 5, 6, 7, 8 },
                       { 9, 10, 11, 12 },
                       { 13, 14, 15, 16 } };
    int K = 2;
    int S = 14;
  
    if (sumFound(K, S, grid))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GfG
{
    static int N = 4;
  
    // Function to return the sum of the sub-matrix
    static int getSum(int r1, int r2, 
                       int c1, int c2, int dp[][]) 
    {
        return dp[r2][c2] - dp[r2][c1]
                - dp[r1][c2] + dp[r1][c1];
    }
  
    // Function that returns true if it is possible
    // to find the sub-matrix with required sum
    static boolean sumFound(int K, int S, int grid[][])
    {
  
        // 2-D array to store the sum of
        // all the sub-matrices
        int dp[][] = new int[N + 1][N + 1];
  
        // Filling of dp[][] array
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1]
                        - dp[i][j] + grid[i][j];
            }
        }
  
        // Checking for each possible sub-matrix of size k X k
        for (int i = 0; i < N; i += K)
        {
            for (int j = 0; j < N; j += K) 
            {
                int sum = getSum(i, i + K, j, j + K, dp);
  
                if (sum == S) 
                {
                    return true;
                }
            }
        }
  
        // Sub-matrix with the given sum not found
        return false;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int grid[][] = {{1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12},
                        {13, 14, 15, 16}};
        int K = 2;
        int S = 14;
  
        if (sumFound(K, S, grid))
        {
            System.out.println("Yes");
        
        else 
        {
            System.out.println("No");
        }
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of the approach
N = 4
  
# Function to return the sum of the sub-matrix
def getSum(r1, r2, c1, c2, dp):
    return dp[r2][c2] - dp[r2][c1] - dp[r1][c2] + dp[r1][c1]
  
  
# Function that returns true if it is possible
# to find the sub-matrix with required sum
def sumFound(K, S, grid):
      
    # 2-D array to store the sum of
    # all the sub-matrices
    dp = [[0 for i in range(N+1)] for j in range(N+1)]
  
    # Filling of dp[][] array
    for i in range(N):
        for j in range(N):
            dp[i + 1][j + 1] = dp[i + 1][j] + \
                dp[i][j + 1] - dp[i][j] + grid[i][j]
  
    # Checking for each possible sub-matrix of size k X k
    for i in range(0, N, K):
        for j in range(0, N, K):
            sum = getSum(i, i + K, j, j + K, dp)
            if (sum == S):
                return True
                  
    # Sub-matrix with the given sum not found
    return False
  
  
# Driver code
grid = [[1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]]
K = 2
S = 14
if (sumFound(K, S, grid)):
    print("Yes")
else:
    print("No")
  
# This code is contributed by ankush_953

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
      
class GfG
{
    static int N = 4;
  
    // Function to return the sum of the sub-matrix
    static int getSum(int r1, int r2, 
                    int c1, int c2, int [,]dp) 
    {
        return dp[r2,c2] - dp[r2,c1]
                - dp[r1,c2] + dp[r1,c1];
    }
  
    // Function that returns true if it is possible
    // to find the sub-matrix with required sum
    static bool sumFound(int K, int S, int [,]grid)
    {
  
        // 2-D array to store the sum of
        // all the sub-matrices
        int [,]dp = new int[N + 1,N + 1];
  
        // Filling of dp[,] array
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                dp[i + 1,j + 1] = dp[i + 1,j] + dp[i,j + 1]
                        - dp[i,j] + grid[i,j];
            }
        }
  
        // Checking for each possible sub-matrix of size k X k
        for (int i = 0; i < N; i += K)
        {
            for (int j = 0; j < N; j += K) 
            {
                int sum = getSum(i, i + K, j, j + K, dp);
  
                if (sum == S) 
                {
                    return true;
                }
            }
        }
  
        // Sub-matrix with the given sum not found
        return false;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        int [,]grid = {{1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12},
                        {13, 14, 15, 16}};
        int K = 2;
        int S = 14;
  
        if (sumFound(K, S, grid))
        {
            Console.WriteLine("Yes");
        
        else
        {
            Console.WriteLine("No");
        }
    }
}
  
// This code has been contributed by 29AjayKumar

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP implementation of the approach 
  
$GLOBALS['N'] = 4; 
  
// Function to return the sum of 
// the sub-matrix 
function getSum($r1, $r2, $c1, $c2, $dp)
{
    return $dp[$r2][$c2] - $dp[$r2][$c1] - 
           $dp[$r1][$c2] + $dp[$r1][$c1]; 
}
  
// Function that returns true if it is 
// possible to find the sub-matrix with 
// required sum 
function sumFound($K, $S, $grid
  
    // 2-D array to store the sum of 
    // all the sub-matrices 
    $dp = array(array());
      
    for ($i = 0; $i < $GLOBALS['N']; $i++) 
        for ($j = 0; $j < $GLOBALS['N']; $j++) 
            $dp[$i][$j] = 0 ;
  
    // Filling of dp[][] array 
    for ($i = 0; $i < $GLOBALS['N']; $i++) 
        for ($j = 0; $j < $GLOBALS['N']; $j++) 
            $dp[$i + 1][$j + 1] = $dp[$i + 1][$j] + 
                                  $dp[$i][$j + 1] - 
                                  $dp[$i][$j] + 
                                  $grid[$i][$j]; 
  
    // Checking for each possible sub-matrix
    // of size k X k 
    for ($i = 0;
         $i < $GLOBALS['N']; $i += $K
        for ($j = 0; 
             $j < $GLOBALS['N']; $j += $K)
        
            $sum = getSum($i, $i + $K, $j,
                          $j + $K, $dp); 
  
            if ($sum == $S
                return true; 
        
  
    // Sub-matrix with the given
    // sum not found 
    return false; 
  
// Driver code 
$grid = array(array(1, 2, 3, 4), 
              array(5, 6, 7, 8), 
              array(9, 10, 11, 12), 
              array(13, 14, 15, 16)); 
$K = 2; 
$S = 14; 
  
if (sumFound($K, $S, $grid)) 
    echo "Yes"
else
    echo "No";
  
// This code is contributed by Ryuga
?>

chevron_right


Output:

Yes


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.