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.
Problem Solving Ideas:
Dynamic programming m is the matrix row, and n is the matrix column where the matrix is empty.
Establish ACCU = new Int[m+1][n+1], first row and first column 0
Value of each coordinate recurrence formula:accu[i][j] = Accu[i-1][j] + accu[i][j-1]-accu[i-1][j-1] + matrix[i-1][j-1]
The selected rectangle interval drawing indicates that the values are determined by 4 vertices,
Formula: Accu[row2+1][col2+1]-accu[row2+1][col1]-accu[row1][col2+1] + accu[row1][col1]
Java Code:
Public classNummatrix {Private int[] accu; PublicNummatrix (int[] matrix) { if(Matrix = =NULL|| Matrix.length = = 0) { return; } intm =matrix.length; intn = matrix[0].length; Accu=New int[M+1] [N+1]; //base Case first Row/column are 0 default is 0 for(inti = 1; i<= m; i++){ for(intj = 1; J <= N; J + +) {Accu[i][j]= Accu[i-1][j] + accu[i][j-1]-accu[i-1][j-1] + matrix[i-1][j-1]; } } } Public intSumregion (intRow1,intCol1,intRow2,intcol2) { returnACCU[ROW2+1][COL2+1]-accu[row2+1][col1]-accu[row1][col2+1] +Accu[row1][col1]; }}//Your Nummatrix object would be instantiated and called as such://Nummatrix Nummatrix = new Nummatrix (matrix);//nummatrix.sumregion (0, 1, 2, 3);//nummatrix.sumregion (1, 2, 3, 4);
Reference:
1. Https://leetcode.com/discuss/69054/dp-java-solution
2. Https://leetcode.com/discuss/69315/an-easy-c-dp-solution-with-simple-explanation
Leetcode Range Sum Query 2d-immutable