[LeetCode] 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.

Example 1:

Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]
Output: [[1,1,0],[1,2,1],[0,1,1]]
Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).

Example 2:

Input: n = 2, queries = [[0,0,1,1]]
Output: [[1,1],[1,1]]
Explanation: The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.

Constraints:

  • 1 <= n <= 500
  • 1 <= queries.length <= 104
  • 0 <= row1i <= row2i < n
  • 0 <= col1i <= col2i < n

子矩阵元素加 1。

给你一个正整数 n ,表示最初有一个 n x n 、下标从 0 开始的整数矩阵 mat ,矩阵中填满了 0 。

另给你一个二维整数数组 query 。针对每个查询 query[i] = [row1i, col1i, row2i, col2i] ,请你执行下述操作:

找出 左上角 为 (row1i, col1i) 且 右下角 为 (row2i, col2i) 的子矩阵,将子矩阵中的 每个元素 加 1 。也就是给所有满足 row1i <= x <= row2i 和 col1i <= y <= col2i 的 mat[x][y] 加 1 。
返回执行完所有操作后得到的矩阵 mat 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/increment-submatrices-by-one
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是二维差分。二维差分可以解决类似这样的问题,比如下图(引用

在一个二维矩阵里,

(a) 如果你想把桔黄色的部分都 + 1,那么就只需要在左上角这个点 + 1,然后遍历整个矩阵,令 grid[i][j] += grid[i][j - 1] 即可

如果你只想让 (b) 图中蓝色的部分都 + 1,那么你需要在图 (c) 的这些位置做加或减的操作,然后再求整个矩阵的前缀和。这道题也是一样的思路,只是注意,需要修改的部分的右下角的坐标不能越界。

时间O(n^2)

空间O(n^2)

Java实现

 1 class Solution {
 2     public int[][] rangeAddQueries(int n, int[][] queries) {
 3         int[][] grid = new int[n][n];
 4         for (int[] q : queries) {
 5             int r1 = q[0];
 6             int c1 = q[1];
 7             int r2 = q[2];
 8             int c2 = q[3];
 9             for (int i = r1; i <= r2; i++) {
10                 grid[i][c1]++;
11                 // 注意不能越界
12                 if (c2 + 1 < n) {
13                     grid[i][c2 + 1]--;
14                 }
15             }
16         }
17 
18         for (int i = 0; i < n; i++) {
19             for (int j = 1; j < n; j++) {
20                 grid[i][j] += grid[i][j - 1];
21             }
22         }
23         return grid;
24     }
25 }

 

LeetCode 题目总结

posted @ 2023-01-17 02:43  CNoodle  阅读(134)  评论(0编辑  收藏  举报