-
Notifications
You must be signed in to change notification settings - Fork 7
/
304-Range-Sum-Query-2D-Immutable.js
49 lines (44 loc) · 1.13 KB
/
304-Range-Sum-Query-2D-Immutable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class NumMatrix {
/**
* @param {number[][]} matrix
*/
constructor(matrix) {
this.dp = this.init(matrix);
}
/**
* @param {number[][]} matrix
* @return {number[][]}
*/
init(matrix) {
const arr = [];
for (let i = 0; i < matrix.length + 1; i++) {
const subArr = [];
for (let j = 0; j < matrix[0].length + 1; j++) {
subArr.push(0);
}
arr.push(subArr);
}
for (let i = 1; i < matrix.length + 1; i++) {
for (let j = 1; j < matrix[0].length + 1; j++) {
arr[i][j] =
matrix[i - 1][j - 1] + arr[i - 1][j] + arr[i][j - 1] - arr[i - 1][j - 1];
}
}
return arr;
}
/**
* @param {number} row1
* @param {number} col1
* @param {number} row2
* @param {number} col2
* @return {number}
*/
sumRegion(row1, col1, row2, col2) {
return (
this.dp[row2 + 1][col2 + 1] -
this.dp[row2 + 1][col1] -
this.dp[row1][col2 + 1] +
this.dp[row1][col1]
);
}
}