1277 Count Square Submatrices with All Ones 統計全為 1 的正方形子矩陣
Description:
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example:
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
Constraints:
1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1
題目描述:
給你一個 m * n 的矩陣,矩陣中的元素不是 0 就是 1,請你統計并返回其中完全由 1 組成的 正方形 子矩陣的個數。
示例:
示例 1:
輸入:matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
輸出:15
解釋:
邊長為 1 的正方形有 10 個。
邊長為 2 的正方形有 4 個。
邊長為 3 的正方形有 1 個。
正方形的總數 = 10 + 4 + 1 = 15.
示例 2:
輸入:matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
輸出:7
解釋:
邊長為 1 的正方形有 6 個。
邊長為 2 的正方形有 1 個。
正方形的總數 = 6 + 1 = 7.
提示:
1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1
思路:
動態規劃
令 dp[i + 1][j + 1] 表示以 matrix[i][j] 為右下角的最大正方形的邊長
dp[i + 1][j + 1] = 0, if matrix[i][j] == 0
dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j], dp[i][j + 1]) + 1, if matrix[i][j] == 1
也就是說右下角的值取決于左上, 上方和左邊的最小值加上自身的長度
將 dp 求和即為結果
注意到, dp[i + 1] 只和當前行和前一行有關, 可以將空間復雜度壓縮到 O(n)
時間復雜度為 O(mn), 空間復雜度為 O(n)
代碼:
C++:
class Solution
{
public:
int countSquares(vector<vector<int>>& matrix)
{
int m = matrix.size(), n = matrix.front().size(), result = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (i and j and matrix[i][j]) matrix[i][j] += min({matrix[i - 1][j - 1], matrix[i - 1][j], matrix[i][j - 1]});
result += matrix[i][j];
}
}
return result;
}
};
Java:
class Solution {
public int countSquares(int[][] matrix) {
int m = matrix.length, n = matrix[0].length, dp[][] = new int[m + 1][n + 1], result = 0;
for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (matrix[i][j] == 1) dp[i + 1][j + 1] = Math.min(dp[i][j + 1], Math.min(dp[i][j], dp[i + 1][j])) + 1;
for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) result += dp[i + 1][j + 1];
return result;
}
}
Python:
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m, dp, result = len(matrix), [0] * ((n := len(matrix[0])) + 1), 0
for i in range(m):
cur = [0] * (n + 1)
for j in range(n):
if matrix[i][j]:
cur[j + 1] = min(dp[j], cur[j], dp[j + 1]) + 1
result += cur[j + 1]
dp = cur
return result