2536. Increment Submatrices by One #2419
-
|
Topics: You are given a positive integer You are also given a 2D integer array
Return the matrix Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to efficiently update a matrix by incrementing all elements in specified submatrices by one for each query. The challenge is to perform these updates optimally without resorting to a brute-force approach, which would be computationally expensive given the constraints. Approach
Let's implement this solution in PHP: 2536. Increment Submatrices by One <?php
/**
* @param Integer $n
* @param Integer[][] $queries
* @return Integer[][]
*/
function rangeAddQueries($n, $queries) {
$mat = array_fill(0, $n, array_fill(0, $n, 0));
$diff = array_fill(0, $n, array_fill(0, $n + 1, 0));
foreach ($queries as $q) {
list($r1, $c1, $r2, $c2) = $q;
for ($i = $r1; $i <= $r2; $i++) {
$diff[$i][$c1] += 1;
if ($c2 + 1 < $n) {
$diff[$i][$c2 + 1] -= 1;
}
}
}
for ($i = 0; $i < $n; $i++) {
$current = 0;
for ($j = 0; $j < $n; $j++) {
$current += $diff[$i][$j];
$mat[$i][$j] = $current;
}
}
return $mat;
}
// Test cases
// Example 1
$n = 3;
$queries = [[1,1,2,2],[0,0,1,1]];
print_r(rangeAddQueries($n, $queries));
// Example 2
$n = 2;
$queries = [[0,0,1,1]];
print_r(rangeAddQueries($n, $queries));
?>Explanation:
|
Beta Was this translation helpful? Give feedback.


We need to efficiently update a matrix by incrementing all elements in specified submatrices by one for each query. The challenge is to perform these updates optimally without resorting to a brute-force approach, which would be computationally expensive given the constraints.
Approach
Problem Analysis: The problem requires updating submatrices defined by each query. A brute-force approach would involve updating each cell in the submatrix for every query, leading to a time complexity of O(q * n²), where q is the number of queries and n is the matrix size. This is inefficient for large n and q.
Key Insight: Instead of updating each cell directly, we can use a difference array for each r…