Open In App

Find sub-matrix with the given sum

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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++)
        for (int j = 0; j < N; j++) {
            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;
 
    // Function call
    if (sumFound(K, S, grid))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}
// Modified by Kartik Verma


Java




// 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++) {
            for (int j = 0; j < N; j++) {
                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;
 
        // Function call
        if (sumFound(K, S, grid)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}
 
// This code contributed by Rajput-Ji
// Modified by Kartik Verma


Python3




# 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):
        for j in range(0, N):
            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
 
# Function call
if (sumFound(K, S, grid)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by ankush_953
# Modified by Kartik Verma


C#




// 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++) {
            for (int j = 0; j < N; j++) {
                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;
 
        // Function call
        if (sumFound(K, S, grid)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}
 
// This code has been contributed by 29AjayKumar
// Modified by Kartik Verma


PHP




<?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++)
        for ($j = 0;
             $j < $GLOBALS['N']; $j++)
        {
            $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;
 
// Function call
if (sumFound($K, $S, $grid))
    echo "Yes";
else
    echo "No";
 
// This code is contributed by Ryuga
//Modified by Kartik Verma
?>


Javascript




<script>
 
// Javascript implementation of the approach
 
var 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
    var dp = Array.from(Array(N+1), ()=> Array(N+1).fill(0));
 
    // Filling of dp[][] array
    for (var i = 0; i < N; i++)
        for (var 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 (var i = 0; i < N; i++)
        for (var j = 0; j < N; j++) {
            var 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
var grid = [ [ 1, 2, 3, 4 ],
                   [ 5, 6, 7, 8 ],
                   [ 9, 10, 11, 12 ],
                   [ 13, 14, 15, 16 ] ];
var K = 2;
var S = 14;
// Function call
if (sumFound(K, S, grid))
    document.write( "Yes");
else
    document.write( "No" );
 
</script>


Output

Yes


Last Updated : 16 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads