Given an M × N integer matrix and two coordinates (p, q) and (r, s) representing top-left and bottom-right coordinates of a submatrix of it, calculate the sum of all elements present in the submatrix. Here, 0 <= p < r < M and 0 <= q < s < N.

For example,

Input: matrix[][] is
 
[ 0  2  5  4  1 ]
[ 4  8  2  3  7 ]
[ 6  3  4  6  2 ]
[ 7  3  1  8  3 ]
[ 1  5  7  9  4 ]
 
(p, q) = (1, 1)
(r, s) = (3, 3)
 
 
Output: Sum is 38
 
Explanation:
 
The submatrix formed by coordinates (p, q), (p, s), (r, q), and (r, s) is shown below, having the sum of elements equal to 38.
 
[ 8  2  3 ]
[ 3  4  6 ]
[ 3  1  8 ]

Assume that m such lookup calls are made to the matrix; the task is to achieve O(1) time lookups.

Practice this problem

 
The idea is to preprocess the matrix. Take an auxiliary matrix sum[][], where sum[i][j] will store the sum of elements in the matrix from (0, 0) to (i, j). We can easily calculate the value of sum[i][j] in constant time using the following relation:

sum[i][j] = sum[i][j – 1] + sum[i – 1][j] + mat[i][j] – sum[i – 1][j – 1]

The following diagram easily explains this relation. (Here greyed portion represents the sum of elements in the matrix from (0, 0) to (i, j))

 
Submatrix Sum
 

Now to calculate the sum of elements present in the submatrix formed by coordinates (p, q), (p, s), (r, q), and (r, s) in constant time, we can directly apply the relation below:

total = sum[r][s] – sum[r][q – 1] – sum[p – 1][s] + sum[p – 1][q – 1]

The following diagram explains this relation. (Here the greyed portion represent the submatrix).

 
Sum of elements in submatrix

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

38

Java


Download  Run Code

Output:

38

Python


Download  Run Code

Output:

38

This solution takes O(N2) time for an N × N matrix, but we can do constant-time lookups any number of times once the matrix is preprocessed. In other words, if M lookup calls are made to the matrix, then the naive solution takes O(M × N2) time, while the above solution takes only O(M + N2) time.

 
Exercise:

1. Given an M × N integer matrix, find the sum of all K × K submatrix

2. Given an M × N integer matrix and a cell (i, j), find the sum of all matrix elements in constant time, except the elements present at row i and column j of the matrix.