Similar Problems

Similar Problems not available

Increment Submatrices By One - Leetcode Solution

Companies:

LeetCode:  Increment Submatrices By One Leetcode Solution

Difficulty: Medium

Topics: matrix prefix-sum array  

Problem Description: Given a matrix of integers, matrix, representing the 2D grid of integers, you need to increment all the submatrices by 1.

A submatrix is defined as a contiguous group of cells within the matrix. Each cell in the matrix can be incremented by 1.

Solution:

The problem defines the objective of incrementing the sub-matrix which means we need to traverse through each element of the matrix, and summing up the value of all the elements coming in the sub-matrix.

Let's say if we have a 3x3 matrix of integers:

Original Matrix: 1 2 3 4 5 6 7 8 9

Once we perform the sub-matrix increment operation over it, it will be converted to this matrix:

Output Matrix: 10 15 20 23 28 33 36 41 46

As, we know we need to increment all sub-matrices by one, we will run two 'for loops' to traverse across all matrix elements.

The first 'for loop' would move row-wise while the second would move column-wise. We can run an inner loop to obtain a submatrix from a given pair of indices from the outer loop.

Here is how we can solve the problem:

  1. Read the matrix representation 'mat' of the input.
  2. Initialize an empty 2-dimensions container called 'res' which will store the required output and will be used while returning the final result.
  3. Run two 'for loops' to traverse across all matrix elements: i and j (where i is the row, and j is the column).
  4. Now initialize a variable 'sum' for each sub-matrix sum and iterate 'k' with value from 1 upto the minimum length of row and column in the sub-matrix from element (i=0, j=0) upto (i,j), after which we add the sum computed in the 'res' with value 1.
  5. At the end, we return the container 'res' which will store the incremented submatrices.

Here is the Python code to solve the problem:

class Solution: def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) res = [[0] * n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            for x in range(max(0, i-k), min(m, i+k+1)):
                for y in range(max(0, j-k), min(n, j+k+1)):
                    res[i][j] += mat[x][y]
    return res

Time Complexity: O(mnk^2) Space Complexity: O(m*n)

Where, m : number of rows n : number of columns k : the size of the submatrix

Increment Submatrices By One Solution Code

1