1277. Count Square Submatrices with All Ones #755
-
Topics: Given a Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use Dynamic Programming (DP) to keep track of the number of square submatrices with all ones that can end at each cell in the matrix. Here's the approach to achieve this:
Let's implement this solution in PHP: 1277. Count Square Submatrices with All Ones <?php
/**
* @param Integer[][] $matrix
* @return Integer
*/
function countSquares($matrix) {
$m = count($matrix);
$n = count($matrix[0]);
$dp = array_fill(0, $m, array_fill(0, $n, 0));
$totalSquares = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($matrix[$i][$j] == 1) {
if ($i == 0 || $j == 0) {
// If it's on the first row or first column
$dp[$i][$j] = 1;
} else {
$dp[$i][$j] = min($dp[$i - 1][$j], $dp[$i][$j - 1], $dp[$i - 1][$j - 1]) + 1;
}
$totalSquares += $dp[$i][$j];
}
}
}
return $totalSquares;
}
// Test the function with example inputs
$matrix1 = [[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]];
$matrix2 = [[1, 0, 1], [1, 1, 0], [1, 1, 0]];
echo "Output for matrix1: " . countSquares($matrix1) . "\n"; // Expected: 15
echo "Output for matrix2: " . countSquares($matrix2) . "\n"; // Expected: 7
?> Explanation:
This solution is efficient and meets the constraints provided in the problem. |
Beta Was this translation helpful? Give feedback.
We can use Dynamic Programming (DP) to keep track of the number of square submatrices with all ones that can end at each cell in the matrix. Here's the approach to achieve this:
DP Matrix Definition:
dp
wheredp[i][j]
represents the size of the largest square submatrix with all ones that has its bottom-right corner at cell(i, j)
.Transition Formula:
(i, j)
in the matrix:matrix[i][j]
is 1, the value ofdp[i][j]
depends on the minimum of the squares that can be formed by extending from(i-1, j)
,(i, j-1)
, and(i-1, j-1)
. The transition formula is:matrix[i][j]
is 0,dp[i][j]
will be 0…