LeetCode 题解工作台

统计全为 1 的正方形子矩阵

给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1 ,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。 示例 1: 输入: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] 输出: 15 解释: 边长为 1 的正方形有 10 个。 边长为…

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们定义 为以 为右下角的正方形子矩阵的边长,初始时 $f[i][j] = 0$,答案为 $\sum_{i,j} f[i][j]$。 考虑 如何进行状态转移。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 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
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 为以 (i,j)(i,j) 为右下角的正方形子矩阵的边长,初始时 f[i][j]=0f[i][j] = 0,答案为 i,jf[i][j]\sum_{i,j} f[i][j]

考虑 f[i][j]f[i][j] 如何进行状态转移。

  • matrix[i][j]=0\text{matrix}[i][j] = 0 时,有 f[i][j]=0f[i][j] = 0
  • matrix[i][j]=1\text{matrix}[i][j] = 1 时,状态 f[i][j]f[i][j] 的值取决于其上、左、左上三个位置的值:
    • 如果 i=0i = 0j=0j = 0,则 f[i][j]=1f[i][j] = 1
    • 否则 f[i][j]=min(f[i1][j1],f[i1][j],f[i][j1])+1f[i][j] = \min(f[i-1][j-1], f[i-1][j], f[i][j-1]) + 1

答案为 i,jf[i][j]\sum_{i,j} f[i][j]

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别为矩阵的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
speed

复杂度分析

指标
时间O(row \cdot col)
空间O(col)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计全为 1 的正方形子矩阵题解:状态·转移·动态规划 | LeetCode #1277 中等