Given a 2D matrix matrix, handle multiple queries of the following type:
Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Implement the NumMatrix class:
NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Example 1:
- Input :["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]: [[[[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]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]
- Output : [null, 8, 11, 12]
- Explanation : NumMatrix numMatrix = new NumMatrix([[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]]);
m == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-104 <= matrix[i][j] <= 104
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
At most 104 calls will be made to sumRegion
/**
* @param {number[][]} matrix
*/
var NumMatrix = function(matrix) {
this.matrix=matrix
};
/**
* @param {number} row1
* @param {number} col1
* @param {number} row2
* @param {number} col2
* @return {number}
*/
NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
let sum=0;
for(let i=row1; i<=row2; i++){
for(let j=col1; j<=col2; j++){
sum+=this.matrix[i][j]
}
}
return sum
};
bruteForce 방식으로 무지성으로 row1 ~ row2 , col1~ col2까지 더하는 방식이다.
/**
* @param {number[][]} matrix
*/
var NumMatrix = function(matrix) {
const dp = Array.from({length:matrix.length+1}, ()=>Array.from({length:matrix[0].length+1},()=>0));
for(let i=0;i<matrix.length;i++){
for(let j=0;j<matrix[0].length;j++){
dp[i+1][j+1]=(j==0)?matrix[i][j]:dp[i+1][j]+matrix[i][j]
}
}
for(let i=0;i<matrix[0].length;i++){
for(let j=0 ;j<matrix.length;j++){
dp[j+1][i+1]=(j==0)?dp[j+1][i+1]:dp[j][i+1]+dp[j+1][i+1]
}
}
this.dp=dp
this.matrix=matrix
};
/**
* @param {number} row1
* @param {number} col1
* @param {number} row2
* @param {number} col2
* @return {number}
*/
NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
let sum= this.dp[row2+1][col2+1]+this.dp[row1][col1]-this.dp[row2+1][col1]-this.dp[row1][col2+1];
return sum
};
/**
* Your NumMatrix object will be instantiated and called as such:
* var obj = new NumMatrix(matrix)
* var param_1 = obj.sumRegion(row1,col1,row2,col2)
*/
dp 방식으로 행과 열까지의 합을 dp에 미리 계산해 놓고, a-(b+c-d)계산 한번을 통해 값을 구할 수 있다.
아래와 같이 약 10배 이상의 효율성을 보인다.