Leetcode 1504: Count Submatrices With All Ones

grid47
grid47
Exploring patterns and algorithms
Jun 9, 2024 6 min read

You are given a binary matrix of size m x n where each element is either 0 or 1. Your task is to count how many submatrices consist entirely of 1s.
Problem
Approach
Steps
Complexity
Input: You are given a matrix of size m x n, where each element is either 0 or 1. The task is to count all submatrices that contain only 1s.
Example: mat = [[1,0,1],[1,1,0],[1,1,0]]
Constraints:
• 1 <= m, n <= 150
• Each mat[i][j] is either 0 or 1.
Output: The output should be an integer representing the number of submatrices that consist entirely of 1s.
Example: 10
Constraints:
• The number of submatrices is a non-negative integer.
Goal: The goal is to calculate the number of submatrices consisting entirely of 1s by iterating through each potential rectangle.
Steps:
• For each cell in the matrix, calculate the number of submatrices that can end at that cell.
• For each row, maintain the number of consecutive 1s up to that cell to efficiently calculate submatrices.
• Sum up the counts of all submatrices formed by each cell.
Goal: The matrix has dimensions m x n, where both m and n can be as large as 150. Each element of the matrix is either 0 or 1.
Steps:
• 1 <= m, n <= 150
• Each element in the matrix is either 0 or 1.
Assumptions:
• The matrix may contain a mix of 1s and 0s, and its size can vary.
Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Explanation: The total number of submatrices made entirely of 1s is 10.

Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Explanation: The total number of submatrices made entirely of 1s is 16.

Link to LeetCode Lab


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