1504. Count Submatrices With All Ones #2078
-
Topics: Given an Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of submatrices in a given binary matrix that consist entirely of ones. The approach involves dynamically updating the height of consecutive ones in each column for every row and then calculating the number of valid submatrices that end at each row. Approach
Let's implement this solution in PHP: 1504. Count Submatrices With All Ones <?php
/**
* @param Integer[][] $mat
* @return Integer
*/
function numSubmat($mat) {
$m = count($mat);
$n = count($mat[0]);
$h = array_fill(0, $n, 0);
$total = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($mat[$i][$j] == 1) {
$h[$j]++;
} else {
$h[$j] = 0;
}
}
for ($j = 0; $j < $n; $j++) {
$min = $h[$j];
$total += $min;
for ($k = $j - 1; $k >= 0; $k--) {
if ($h[$k] < $min) {
$min = $h[$k];
}
$total += $min;
}
}
}
return $total;
}
// Test cases
// Example 1
$mat1 = [[1,0,1],[1,1,0],[1,1,0]];
echo numSubmat($mat1) . "\n"; // Output: 13
// Example 2
$mat2 = [[0,1,1,0],[0,1,1,1],[1,1,1,0]];
echo numSubmat($mat2) . "\n"; // Output: 24
?> Explanation:
This approach efficiently counts all valid submatrices by leveraging dynamic programming and iterative height updates, ensuring optimal performance even for the upper constraint limits. The complexity is O(m*n2), which is feasible given the constraints. |
Beta Was this translation helpful? Give feedback.
We need to count the number of submatrices in a given binary matrix that consist entirely of ones. The approach involves dynamically updating the height of consecutive ones in each column for every row and then calculating the number of valid submatrices that end at each row.
Approach
h
to keep track of the number of consecutive ones ending at each column for the current row. This array is updated for each row in the matrix.h
array. If the current element is1
, increment the height of the corresponding column; otherwise, reset it to0
.h
array, iterate through…