LeetCode 题解工作台
统计全为 1 的正方形子矩阵
给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1 ,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。 示例 1: 输入: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] 输出: 15 解释: 边长为 1 的正方形有 10 个。 边长为…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 为以 为右下角的正方形子矩阵的边长,初始时 $f[i][j] = 0$,答案为 $\sum_{i,j} f[i][j]$。 考虑 如何进行状态转移。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个 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 <= 3001 <= arr[0].length <= 3000 <= arr[i][j] <= 1
解题思路
方法一:动态规划
我们定义 为以 为右下角的正方形子矩阵的边长,初始时 ,答案为 。
考虑 如何进行状态转移。
- 当 时,有 。
- 当 时,状态 的值取决于其上、左、左上三个位置的值:
- 如果 或 ,则 。
- 否则 。
答案为 。
时间复杂度 ,空间复杂度 。其中 和 分别为矩阵的行数和列数。
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i, row in enumerate(matrix):
for j, v in enumerate(row):
if v == 0:
continue
if i == 0 or j == 0:
f[i][j] = 1
else:
f[i][j] = min(f[i - 1][j - 1], f[i - 1][j], f[i][j - 1]) + 1
ans += f[i][j]
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(row \cdot col) |
| 空间 | O(col) |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate understanding of dynamic programming and how state transition works in this context.
- question_mark
Look for awareness of space optimization techniques, particularly reducing a 2D DP table to 1D.
- question_mark
The ability to handle edge cases, such as matrices with no ones or matrices that are very large, will indicate strong problem-solving skills.
常见陷阱
外企场景- error
Misunderstanding the recurrence relation and incorrectly calculating the DP values.
- error
Failing to optimize space complexity, leading to excessive memory usage.
- error
Not summing the values in the DP table correctly to count the total number of square submatrices.
进阶变体
外企场景- arrow_right_alt
Matrix with larger dimensions (e.g., 500x500) to test efficiency and space optimization.
- arrow_right_alt
Matrix where all elements are 1, which will test if the DP approach can correctly count all possible submatrices.
- arrow_right_alt
Matrix with random placements of 1's and 0's to ensure robustness of the solution under various configurations.