221. Maximal Square -Medium
来源:互联网 发布:数据库第六版中文答案7 编辑:程序博客网 时间:2024/06/02 04:53
Question
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
给出一个二维矩阵,元素由0,1组成,找到最大的仅由1组成的正方形,返回其面积大小
Example
given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
Solution
动态规划解。对于矩阵的每个元素,判断是否能够形成正方形主要看其左边,上边,左上边元素的值,如果都为‘1’,那么就会形成边长为2的正方形。所以根据这个思路我们定义dp[i][j]:以(i,j)为结尾的正方形的最大边长。
如果matrix[i][j] = ‘0’ ,那么代表不可能形成正方形,dp[i][j] = 0
如果matrix[i][j] = ‘1’,那么至少能形成边长为1的正方形,而以它结尾的正方形最大多大的递推式为dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1。假设左,上,左上的坐标的最大正方形边长都为1,那么dp[i][j]就会是2,即一个边长为2的正方形;如果三个边长为0,1,1,那么dp[i][j]就会是1,即它本身(一个边长为1的正方形)
class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if len(matrix) == 0: return 0 dp = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)] max_size = 0 for index_r in range(1, len(matrix) + 1): for index_c in range(1, len(matrix[0]) + 1): # 当前元素是否为‘1’(因为dp的行列都增加了1,所以这里需要-1) if matrix[index_r - 1][index_c - 1] == '1': dp[index_r][index_c] = min(dp[index_r - 1][index_c], dp[index_r][index_c - 1], dp[index_r - 1][index_c - 1]) + 1 max_size = max(max_size, dp[index_r][index_c]) # 记录最大的正方形边长 return max_size * max_size
0 0
- 【Medium】221. Maximal Square
- 221. Maximal Square -Medium
- Leetcode 221. Maximal Square (Medium) (cpp)
- [Medium]Maximal Square
- [Leetcode 221, Medium] Maximal square
- Medium 221题 Maximal Square
- 221.Maximal Square
- [leetcode] 221.Maximal Square
- 【leetcode】221. Maximal Square
- [LeetCode]221. Maximal Square
- leetcode 221. Maximal Square
- 221. Maximal Square LeetCode
- 221. Maximal Square
- 221. Maximal Square
- LeetCode 221. Maximal Square
- 221. Maximal Square
- LeetCode *** 221. Maximal Square
- 221. Maximal Square
- JSP
- Tiny4412 开发环境搭建(一)
- 认识iOS的RunLoop
- 语料处理之全角转半角
- 学习笔记
- 221. Maximal Square -Medium
- java垃圾回收机制(二)
- 图像处理之每日一练:噪声的添加和过滤
- Handler详解
- 2017.2.11【初中部 GDKOI】模拟赛B组题解
- 1112. Stucked Keyboard (20) -- 字符串处理,使用map
- 什么情况下用标准梯度下降法,什么情况下用随机梯度下降法
- 安装JDK,配置环境变量
- java代码规范