Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by it upper left corner ( row1, Col1) and lower right corner ( row2, Col2).
The above rectangle (with the red border) are defined by (row1, col1) = (2, 1) and (Row2, col2) = (4, 3), which contains Su m = 8.
Example:
Given matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]] Sumregion (2, 1, 4, 3), 8sumRegion (1, 1, 2, 2), 11sumRegion (1, 2, 2, 4), 12
Note:
- Assume that the matrix does not a change.
- There is many calls to sumregion function.
- Assume that row1≤ row2 and Col1≤ Col2.
The problem has appeared in the beauty of programming. The matrix can be considered as a square in the geometry, and the sub-matrices are evaluated in terms of area. The main is to deal with the boundary index.
Can be compared with one-dimensional topics. Link:
303. Range Sum query-immutable Java Solutions
1 Public classNummatrix {2 Private int[] sum;3 BooleanHasnum =true;4 PublicNummatrix (int[] matrix) {5 if(Matrix.length = = 0 | | matrix[0].length = = 0){6Hasnum =false;7 return;8 }9sum =New int[Matrix.length+1] [Matrix[0].length+1];Ten for(inti = 0; i < sum.length; i++){ OneSum[i][0] = 0; A } - for(inti = 1; i < sum[0].length; i++){ -Sum[0][i] = 0; the } - for(inti = 1; i < sum.length; i++){ - for(intj = 1; J < Sum[0].length; J + +){ -SUM[I][J] = Sum[i-1][j] + sum[i][j-1]-sum[i-1][j-1] + matrix[i-1][j-1]; + } - } + } A at Public intSumregion (intRow1,intCol1,intRow2,intcol2) { - if(!hasnum)return0; - returnSUM[ROW2+1][COL2+1]-sum[row2+1][col1]-sum[row1][col2+1] +Sum[row1][col1]; - } - } - in - //Your Nummatrix object would be instantiated and called as such: to //Nummatrix Nummatrix = new Nummatrix (matrix); + //nummatrix.sumregion (0, 1, 2, 3); - //nummatrix.sumregion (1, 2, 3, 4);
304. Range Sum Query 2d-immutable Java Solutions