# Print cells with same rectangular sums in a matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a matrix mat of size mXn of integer values. Our task is to create a program to Print cells with same rectangular sums in a matrix.

Problem description: We will be finding a cell in the matrix in such a way that the sum of sub-matrices that are starting and ending with the cell is equal to the sum of all the remaining elements.

For a cell the sum of matrix (a, b) sub-matrix mat[0][0] to mat[a][b] and mat[a][b] to mat[m][n] is equal to the sum of all remaining elements.

Let’s take an example to understand the problem,

Input: mat[][] = { {5, 0, 2, 7}
{3, 0, 1, 0}
{1, 4, 1, 3}
{10, 0, 2, 1}}

Output: (2, 1)

Explanation:

For the element (2,3)

Submatrix1 is - {   {5, 0}
{3, 0}
{1, 4}}

Submatrix2 is - {   {4, 1, 3}
{0, 2, 1}}

Sum = 5 + 0 + 3 + 0 + 1 + 4 + 1 + 3 + 0 + 2 + 1 = 20

Sum of rest of the elements = 2 + 7 + 1 + 0 + 10  = 20

## Solution Approach

To solve the problem, we need to create 2 auxiliary sub-matrices, aux1[m][n] and aux2[m][n]. The aux1[i][j] will store the sum of all elements from (0,0) to (i, j) and aux2[i][j] will store the sum of all elements from (i,j) to (n, m). Then we will add both the sums and subtract mat(i,j) as it will occur twice.

Then we will compare this sum with the sum of all elements of the matrix. If the sum at the cell is half the sum of the matrix. Then the cell is the result, and we will print it.

## Example

Live Demo

#include <iostream>
using namespace std;
#define R 4
#define C 4

void findCellWithSameRectSum(int mat[R][C]) {

int m = R, n = C;
int aux1[m][n], aux2[m][n];
int matSum = 0;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {

aux2[i][j] = aux1[i][j] = mat[i][j];
matSum += mat[i][j];

}
}

for (int i = 1; i < m; i++) {

aux1[i][0] += aux1[i-1][0];
aux2[m-i-1][n-1] += aux2[m-i][n-1];
}

for (int j = 1; j < n; j++) {

aux1[0][j] += aux1[0][j-1];
aux2[m-1][n-j-1] += aux2[m-1][n-j];
}

for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++) {

aux1[i][j] += aux1[i-1][j] + aux1[i][j-1] - aux1[i-1][j-1];
aux2[m-i-1][n-j-1] += aux2[m-i][n-j-1] + aux2[m-i-1][n-j] - aux2[m-i][n-j];
}

for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (matSum == 2 * (aux1[i][j] + aux2[i][j] - mat[i][j]))
cout << "(" << i << ", " << j << ")\t";
}

int main() {
int mat[R][C] = {{5, 0, 2, 7},
{3, 0, 1, 0},
{1, 4, 1, 3},
{10, 0, 2, 1}};
cout<<"The cells with same rectangular sums in a matrix is \n";
findCellWithSameRectSum(mat);

return 0;
}

## Output

The cells with same rectangular sums in a matrix is
(1, 1)           (2, 1)
Published on 25-Jan-2021 05:24:12