[LeetCode] Increment Submatrices by One

2536. Increment Submatrices by One

You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes.

You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation:

  • Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom right corner (row2i, col2i). That is, add 1 to mat[x][y] for for all row1i <= x <= row2i and col1i <= y <= col2i.

Return the matrix mat after performing every query.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
vector<vector<int>> res(n,vector<int>(n));
for(auto q : queries) {
int y1 = q[0], x1 = q[1], y2 = q[2], x2 = q[3];
for(int i = y1; i <= y2; i++) {
res[i][x1] += 1;
if(x2 + 1 < n) res[i][x2+1] -= 1;
}
}
for(int i = 0; i < n; i++) {
for(int j = 1; j < n; j++) res[i][j] += res[i][j-1];
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/01/15/PS/LeetCode/increment-submatrices-by-one/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.