一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情。
描述
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
复制代码
Example 2:
Input: matrix = [["0","1"],["1","0"]]
Output: 1
复制代码
Note:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] is '0' or '1'.
复制代码
解析
根据题意,给出了一个 m x n 的矩阵 matrix ,里面每个格子填充了 0 或者 1 ,找到只包含 1 的最大的正方形面积并返回。其实这道题一看完题目,我们就能知道这种数数的题目基本上用动态规划会比较方便一点,我们定义 dp[i][j] 为以此位置做右下角的正方形的最大边长,公式为:
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
复制代码
用图展示会更加清楚:
最后只需要找到 dp 中的最大值作为正方形边长,得到正方形的最大面积即可。其实如果是经常刷题的朋友应该知道,这道题和 1277. Count Square Submatrices with All Ones 几乎一样。
解答
import numpy
class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
M = len(matrix)
N = len(matrix[0])
dp = [[0] * N for _ in range(M)]
for n in range(N):
dp[0][n] = int(matrix[0][n])
for m in range(M):
dp[m][0] = int(matrix[m][0])
for i in range(1, M):
for j in range(1, N):
if matrix[i][j] == '0':
continue
dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
L = numpy.max(dp)
return L * L
复制代码
运行结果
Runtime: 213 ms, faster than 39.94% of Python online submissions for Maximal Square.
Memory Usage: 33.8 MB, less than 6.85% of Python online submissions for Maximal Square.
复制代码
原题链接:leetcode.com/problems/ma…
您的支持是我最大的动力