Leetcode 1277: Count Square Submatrices with All Ones

grid47
grid47
Exploring patterns and algorithms
Jul 2, 2024 4 min read

Given a m x n matrix of ones and zeros, count how many square submatrices are filled with all ones.
Problem
Approach
Steps
Complexity
Input: You are given a 2D matrix where each element is either a 0 or 1.
Example: Input: matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Constraints:
• 1 <= arr.length <= 300
• 1 <= arr[0].length <= 300
• 0 <= arr[i][j] <= 1
Output: Return the total number of square submatrices that are fully filled with ones.
Example: Output: 15
Constraints:
• All submatrices considered must be squares filled with only 1s.
Goal: To calculate the number of square submatrices that consist only of 1s.
Steps:
• Iterate through the matrix and at each cell that contains 1, calculate the largest possible square submatrix that can be formed with that cell as the bottom-right corner.
• The size of the square submatrix is determined by the minimum of the squares possible at the adjacent cells (top, left, top-left diagonal).
• Accumulate the number of squares of all sizes.
Goal: The solution must handle matrices of size up to 300x300 efficiently.
Steps:
• Matrix dimensions: 1 <= arr.length <= 300, 1 <= arr[0].length <= 300
• Each element is either 0 or 1.
Assumptions:
• The matrix is rectangular and may have varying numbers of rows and columns.
• There will be no invalid values in the matrix, i.e., only 0s and 1s.
Input: Input: matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Explanation: The total count of square submatrices is determined by calculating the possible side lengths of squares that can be formed at each position. This includes squares of different sizes such as 1x1, 2x2, and 3x3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus