LeetCode 1277. Count Square Submatrices with All Ones 二维前缀

231 篇文章 0 订阅
120 篇文章 1 订阅

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

---------------------------------

这题和https://blog.csdn.net/taoqick/article/details/104985064 一样,但是反应有些慢:

1. 没想到和与以(i,j)结尾最大square关系,反应有些慢

2. min(pref(i-1,j),pref(i,j-1),pref(i-1,j-1))+1 错写成了min(pref(i-1,j),pref(i,j-1))+1

from typing import List

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        def pref(x,y):
            return 0 if x<0 or y<0 else f[x][y]
        rows,cols = len(matrix),len(matrix[0]) if matrix else 0
        res = 0
        f = [[0 for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                f[i][j] = 0 if matrix[i][j] == 0 else min(pref(i-1,j),pref(i,j-1),pref(i-1,j-1))+1
                res += f[i][j]
        #print(f)
        return res

s = Solution()
print(s.countSquares([
  [1,0,1],
  [1,1,0],
  [1,1,0]
]))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值