Skip to content

Commit 3f64635

Browse files
committed
2 parents c31404d + b8cdf2e commit 3f64635

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class NumMatrix {
2+
/*
3+
T.C. for one query is O(1)
4+
*/
5+
private int[][] dp;
6+
public NumMatrix(int[][] matrix) {
7+
int row = 0;
8+
int col = 0;
9+
if (matrix.length != 0) {
10+
row = matrix.length;
11+
col = matrix[0].length;
12+
}
13+
dp = new int[row+1][col+1];
14+
15+
for (int i=1; i<dp.length; i++) {
16+
for (int j=1; j<dp[0].length; j++) {
17+
// filling up sum of boxes from (0,0) to (i-1,j-1) at dp[i][j]
18+
// vertical box value + horizontal box value + current box value of matrix - (value that included twice)
19+
dp[i][j] = dp[i-1][j] + dp[i][j-1] + matrix[i-1][j-1] - dp[i-1][j-1];
20+
}
21+
}
22+
23+
}
24+
25+
public int sumRegion(int row1, int col1, int row2, int col2) {
26+
row1++;
27+
row2++;
28+
col1++;
29+
col2++;
30+
31+
return dp[row2][col2] - dp[row1-1][col2] - dp[row2][col1-1] + dp[row1-1][col1-1];
32+
}
33+
}
34+
35+
/**
36+
* Your NumMatrix object will be instantiated and called as such:
37+
* NumMatrix obj = new NumMatrix(matrix);
38+
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
39+
*/

0 commit comments

Comments
 (0)