zoukankan      html  css  js  c++  java
  • 221. Maximal Square(dp)

    Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

    Example:

    Input:

    1 0 1 0 0
    1 0 1 1 1
    1 1 1 1 1
    1 0 0 1 0

    Output: 4

    用dp来记录以i,j为右下角元素时最大的matrix。状态转移方程比较trick
    Solution:

    class Solution(object):
        def maximalSquare(self, matrix):
            """
            :type matrix: List[List[str]]
            :rtype: int
            """
            res = 0
            dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
            for i in range(len(matrix)):
                for j in range(len(matrix[0])):
                    dp[i][j] = 1 if matrix[i][j]=='1' else 0
                    if i>0 and j>0 and matrix[i][j]=='1':
                        dp[i][j] = 1 + min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))
                    res = max(res,dp[i][j])
            return res*res
    
  • 相关阅读:
    IO
    多线程
    常用类
    异常
    接口
    面向对象
    面向对象
    学习数组
    for的嵌套循环
    XML:是什么?怎样工作的?可以做什么?将来的发展有会怎样?
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/11178266.html
Copyright © 2011-2022 走看看