Print cells with same rectangular sums in a matrix
Last Updated :
06 Jul, 2022
Given a matrix of m x n matrix, we need to print all those cells at which sum of sub-matrix ended at this cell and sub-matrix starting at this cell is equal to remaining elements. For better understanding please see below diagram,
Examples :
Input : mat[][] = {1, 2, 3, 5,
4, 1, 0, 2,
0, 1, 2, 0,
7, 1, 1, 0};
Output : (1, 1), (2, 2)
In above matrix, cell (1, 1) and cell (2, 2)
are our required cells because,
For cell (1, 1), sum of red and green areas is same
1+2+4+1+0+2+1+2+0+1+1+0 = 3+5+0+7
Same is true for cell (2, 2)
1+2+3+4+1+0+0+1+2+0+1+0 = 5+2+7+1
We need to print all blue boundary cells for
which sum of red area is equal to green area.

First we construct auxiliary sub-matrices similar to the linked article.
We construct two matrices sum[][] and sumr[][] such that sum[i][j] denotes sum of sub-matrix from mat[0][0] to mat[i][j]. And sumr for storing sum till last indices i.e. sumr[i][j] denotes sum of sub-matrix, mat[i][j] to mat[m - 1][n - 1].
Now we can use above matrices for solving this problem, red area shown in above diagram can be calculated by adding corresponding cells from sum and sumr matrices, as mat[i][j] is considered twice while calculating this sum we will subtract it once to get sum of red area. Getting sum of remaining element, the green part, is pretty easy, we will just subtract sum of red part from total sum of given matrix.
So to check whether a particular cell satisfies the given condition we will calculate the sum of red part as explained above and compare it with total sum of matrix, if this sum is half of total sum, current cell satisfies the condition and hence a candidate for result.
Implementation:
C++
// C++ program to print cells with same rectangular
// sum diagonally
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
// Method prints cell index at which rectangular sum is
// same at prime diagonal and other diagonal
void printCellWithSameRectangularArea(int mat[R][C],
int m, int n)
{
/* sum[i][j] denotes sum of sub-matrix, mat[0][0]
to mat[i][j]
sumr[i][j] denotes sum of sub-matrix, mat[i][j]
to mat[m - 1][n - 1] */
int sum[m][n], sumr[m][n];
// Initialize both sum matrices by mat
int totalSum = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
sumr[i][j] = sum[i][j] = mat[i][j];
totalSum += mat[i][j];
}
}
// updating first and last row separately
for (int i = 1; i < m; i++)
{
sum[i][0] += sum[i-1][0];
sumr[m-i-1][n-1] += sumr[m-i][n-1];
}
// updating first and last column separately
for (int j = 1; j < n; j++)
{
sum[0][j] += sum[0][j-1];
sumr[m-1][n-j-1] += sumr[m-1][n-j];
}
// updating sum and sumr indices by nearby indices
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
sum[i][j] += sum[i-1][j] + sum[i][j-1] -
sum[i-1][j-1];
sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] +
sumr[m-i-1][n-j] -
sumr[m-i][n-j];
}
}
// Uncomment below code to print sum and reverse sum
// matrix
/*
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << sum[i][j] << " ";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << sumr[i][j] << " ";
}
cout << endl;
}
cout << endl; */
/* print all those indices at which sum of prime diagonal
rectangles is half of the total sum of matrix */
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
int mainDiagRectangleSum = sum[i][j] + sumr[i][j] -
mat[i][j];
if (totalSum == 2 * mainDiagRectangleSum)
cout << "(" << i << ", " << j << ")" << endl;
}
}
}
// Driver code to test above methods
int main()
{
int mat[R][C] =
{
1, 2, 3, 5,
4, 1, 0, 2,
0, 1, 2, 0,
7, 1, 1, 0
};
printCellWithSameRectangularArea(mat, R, C);
return 0;
}
Java
// Java program to print cells with
// same rectangular sum diagonally
class GFG {
static final int R = 4;
static final int C = 4;
// Method prints cell index at which
// rectangular sum is same at
// prime diagonal and other diagonal
static void printCellWithSameRectangularArea(int mat[][],
int m, int n)
{
/* sum[i][j] denotes sum of sub-matrix, mat[0][0]
to mat[i][j]
sumr[i][j] denotes sum of sub-matrix, mat[i][j]
to mat[m - 1][n - 1] */
int sum[][] = new int[m][n];
int sumr[][] = new int[m][n];
// Initialize both sum matrices by mat
int totalSum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sumr[i][j] = sum[i][j] = mat[i][j];
totalSum += mat[i][j];
}
}
// updating first and last row separately
for (int i = 1; i < m; i++) {
sum[i][0] += sum[i - 1][0];
sumr[m - i - 1][n - 1] += sumr[m - i][n - 1];
}
// updating first and last column separately
for (int j = 1; j < n; j++) {
sum[0][j] += sum[0][j - 1];
sumr[m - 1][n - j - 1] += sumr[m - 1][n - j];
}
// updating sum and sumr indices by nearby indices
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
sum[i][j] += sum[i - 1][j] + sum[i][j - 1] -
sum[i - 1][j - 1];
sumr[m - i - 1][n - j - 1] += sumr[m - i][n - j - 1] +
sumr[m - i - 1][n - j] -
sumr[m - i][n - j];
}
}
// Uncomment below code to print sum and reverse sum
// matrix
/*
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print( sum[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(sumr[i][j] + " ");
}
System.out.println();
}
System.out.println(); */
/* print all those indices at which sum of prime diagonal
rectangles is half of the total sum of matrix */
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int mainDiagRectangleSum = sum[i][j] +
sumr[i][j] - mat[i][j];
if (totalSum == 2 * mainDiagRectangleSum)
System.out.println("(" + i + ", " + j + ")");
}
}
}
// Driver code
public static void main(String[] args)
{
int mat[][] = {{1, 2, 3, 5},
{4, 1, 0, 2},
{0, 1, 2, 0},
{7, 1, 1, 0}};
printCellWithSameRectangularArea(mat, R, C);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to print cells with same rectangular
# sum diagonally
# R 4
# C 4
# Method prints cell index at which rectangular sum is
# same at prime diagonal and other diagonal
def printCellWithSameRectangularArea(mat, m, n):
# sum[i][j] denotes sum of sub-matrix, mat[0][0]
# to mat[i][j]
# sumr[i][j] denotes sum of sub-matrix, mat[i][j]
# to mat[m - 1][n - 1]
sum = [[0 for i in range(m)]for j in range(n)]
sumr = [[0 for i in range(m)]for j in range(n)]
# Initialize both sum matrices by mat
totalSum = 0
for i in range(m):
for j in range(n):
sumr[i][j] = sum[i][j] = mat[i][j];
totalSum += mat[i][j]
# updating first and last row separately
for i in range(1,m):
sum[i][0] += sum[i-1][0]
sumr[m-i-1][n-1] += sumr[m-i][n-1]
# updating first and last column separately
for j in range(1,n):
sum[0][j] += sum[0][j-1];
sumr[m-1][n-j-1] += sumr[m-1][n-j]
# updating sum and sumr indices by nearby indices
for i in range(1,m):
for j in range(1,n):
sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]
sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] + sumr[m-i-1][n-j] - sumr[m-i][n-j]
# Uncomment below code to print sum and reverse sum
# matrix
# print all those indices at which sum of prime diagonal
# rectangles is half of the total sum of matrix
for i in range(m):
for j in range(n):
mainDiagRectangleSum = sum[i][j] + sumr[i][j] - mat[i][j]
if (totalSum == 2 * mainDiagRectangleSum):
print ("(",i,",",j,")")
# Driver code to test above methods
mat =[[1, 2, 3, 5,],
[4, 1, 0, 2,],
[0, 1, 2, 0],
[7, 1, 1, 0]]
printCellWithSameRectangularArea(mat, 4, 4)
# Contributed by Afzal
C#
// C# program to print cells with
// same rectangular sum diagonally
using System;
class GFG {
static int R = 4;
static int C = 4;
// Method prints cell index at which
// rectangular sum is same at
// prime diagonal and other diagonal
static void printCellWithSameRectangularArea(int [,]mat,
int m, int n)
{
/* sum[i][j] denotes sum of sub-
matrix, mat[0][0] to mat[i][j]
sumr[i][j] denotes sum of sub-matrix,
mat[i][j] to mat[m - 1][n - 1] */
int [,]sum = new int[m, n];
int [,]sumr = new int[m, n];
// Initialize both sum matrices by mat
int totalSum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sumr[i, j] = sum[i, j] = mat[i, j];
totalSum += mat[i, j];
}
}
// updating first and last row separately
for (int i = 1; i < m; i++)
{
sum[i, 0] += sum[i - 1, 0];
sumr[m - i - 1, n - 1] += sumr[m - i, n - 1];
}
// updating first and last column separately
for (int j = 1; j < n; j++)
{
sum[0,j] += sum[0,j - 1];
sumr[m - 1,n - j - 1] += sumr[m - 1,n - j];
}
// updating sum and sumr indices by nearby indices
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
sum[i,j] += sum[i - 1,j] + sum[i,j - 1] -
sum[i - 1,j - 1];
sumr[m - i - 1,n - j - 1] += sumr[m - i,n - j - 1] +
sumr[m - i - 1,n - j] -
sumr[m - i,n - j];
}
}
// Uncomment below code to print sum and reverse sum
// matrix
/*
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print( sum[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(sumr[i][j] + " ");
}
System.out.println();
}
System.out.println(); */
/* print all those indices at which sum
of prime diagonal rectangles is half
of the total sum of matrix */
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int mainDiagRectangleSum = sum[i,j] +
sumr[i,j] - mat[i,j];
if (totalSum == 2 * mainDiagRectangleSum)
Console.WriteLine("(" + i + ", " + j + ")");
}
}
}
// Driver code
public static void Main()
{
int [,]mat = {{1, 2, 3, 5},
{4, 1, 0, 2},
{0, 1, 2, 0},
{7, 1, 1, 0}};
printCellWithSameRectangularArea(mat, R, C);
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// Javascript program to print cells with
// same rectangular sum diagonally
let R = 4;
let C = 4;
// Method prints cell index at which
// rectangular sum is same at
// prime diagonal and other diagonal
function printCellWithSameRectangularArea(mat, m, n)
{
/* sum[i][j] denotes sum of sub-matrix, mat[0][0]
to mat[i][j]
sumr[i][j] denotes sum of sub-matrix, mat[i][j]
to mat[m - 1][n - 1] */
let sum = new Array(m);
let sumr = new Array(m);
// Initialize both sum matrices by mat
let totalSum = 0;
for (let i = 0; i < m; i++)
{
sum[i] = new Array(n);
sumr[i] = new Array(n);
for (let j = 0; j < n; j++)
{
sumr[i][j] = sum[i][j] = mat[i][j];
totalSum += mat[i][j];
}
}
// updating first and last row separately
for (let i = 1; i < m; i++)
{
sum[i][0] += sum[i - 1][0];
sumr[m - i - 1][n - 1] += sumr[m - i][n - 1];
}
// updating first and last column separately
for (let j = 1; j < n; j++) {
sum[0][j] += sum[0][j - 1];
sumr[m - 1][n - j - 1] += sumr[m - 1][n - j];
}
// updating sum and sumr indices by nearby indices
for (let i = 1; i < m; i++)
{
for (let j = 1; j < n; j++)
{
sum[i][j] += sum[i - 1][j] + sum[i][j - 1] -
sum[i - 1][j - 1];
sumr[m - i - 1][n - j - 1] += sumr[m - i][n - j - 1] +
sumr[m - i - 1][n - j] -
sumr[m - i][n - j];
}
}
/* print all those indices at which sum of prime diagonal
rectangles is half of the total sum of matrix */
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++)
{
let mainDiagRectangleSum = sum[i][j] +
sumr[i][j] - mat[i][j];
if (totalSum == 2 * mainDiagRectangleSum)
document.write("(" + i + ", " + j + ")" + "</br>");
}
}
}
let mat = [[1, 2, 3, 5],
[4, 1, 0, 2],
[0, 1, 2, 0],
[7, 1, 1, 0]];
printCellWithSameRectangularArea(mat, R, C);
</script>
Time complexity: O(n x m).
Auxiliary Space: O(n x m).
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read