Constrains:
You can't iterate the matrix more than once.
If we name the matrix A then there are two of those matrices available, one is 'read-only' and the other is 'read/write'. We will use the 'read/write' matrix to construct the summed-area table.
For example this code here:
http://www.geeksforgeeks.org/submatrix-sum-queries/
Iterares 2 times: 1) summing all columns 2) summing all rows
Useful picture for summed area tables from Wikipedia:
During construction, we already have
A
,B
andC
(for the edges, they would be zero), and want to computeD
. The area spanned by that rectangle is 1x1 in this case, so we know the sum of the rectangle isX
whereX
is the number from the original matrix at the position ofD
, soD = C + B - A + X
.A
is subtracted because the areas belonging toC
andB
both contain the area ofA
.Simply iterating over the matrix and filling every cell using that formula iterates over the matrix only once, and could even be done in-place (replacing the original matrix by its SAT) if your matrix was not read-only.