[leetcode] 1277. Count Square Submatrices with All Ones

Description

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

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

分析

题目的意思是:给定一个矩阵,求出1区域能够构成正方形的个数。这道题我一开始想着有什么规律,结果发现这些规律都不太对。后面发现是动态规划题目。如果矩阵的当前位置为0,则以它构建的矩阵是0,即dp[i][j]=0,对于其它非0的位置:

dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1

求左上,同行,同列的最小值的值+1,我猜测表示的是当前位置所能构成的正方形的个数,等于其周围最小值的个数+1,这个规律我也不知道怎么推出来的,感觉好像是这个样子,一个位置如果要构成正方形,确实要看左上,上,左,三个位置。

代码

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        m=len(matrix)
        n=len(matrix[0])
        dp=[[0]*(n+1) for i in range(m+1)]
        for i in range(1,m+1):
            for j in range(1,n+1):
                if(matrix[i-1][j-1]==0):
                    dp[i][j]=0
                else:
                    dp[i][j]=min(dp[i][j-1],dp[i-1][j-1],dp[i-1][j])+1
        res=0
        for i in range(m+1):
            for j in range(n+1):
                res+=dp[i][j]
        return res

参考文献

[LeetCode] Count Square Submatrices w/ All ones.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值