LeetCode 1504: Count Submatrices With All Ones Solution
Master LeetCode problem 1504 (Count Submatrices With All Ones), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1504. Count Submatrices With All Ones
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will iterate through the matrix row by row and for each row, we will calculate the number of continuous ones ending at each cell. This information will help us to calculate the number of valid submatrices that end at each cell. By summing up the total count of valid submatrices for each cell, we can get the final answer.
Here are the steps:
- Initialize a 2D array
dpof the same size as the input matrixmatto store the count of continuous ones ending at each cell. - Iterate through each row of the matrix:
- For the first cell of each row, the count of continuous ones ending at that cell will be the value of the cell itself.
- For other cells, if the cell value is 1, update the count by adding the count of the cell to the left.
- Iterate through each cell of the matrix and calculate the total number of valid submatrices ending at that cell by taking the minimum of the continuous ones at that cell and all the cells to its left in the same row.
- Sum up the total count of valid submatrices for each cell to get the final answer.
Time Complexity: O(mn) where m is the number of rows and n is the number of columns in the matrix.
Space Complexity: O(mn) for the dp array.
Solution Code
class Solution {
public int numSubmat(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int[][] dp = new int[m][n];
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j == 0) {
dp[i][j] = mat[i][j];
} else {
dp[i][j] = mat[i][j] == 0 ? 0 : dp[i][j - 1] + 1;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int min = dp[i][j];
for (int k = i; k >= 0 && dp[k][j] > 0; k--) {
min = Math.min(min, dp[k][j]);
count += min;
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1504 (Count Submatrices With All Ones)?
This page provides optimized solutions for LeetCode problem 1504 (Count Submatrices With All Ones) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1504 (Count Submatrices With All Ones)?
The time complexity for LeetCode 1504 (Count Submatrices With All Ones) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1504 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1504 in Java, C++, or Python.