Leetcode 221. Maximal Square

Problem

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.

Algorithm

Dynamic Programming (DP). Tracks the largest square ending at (i,j). The key recurrence relation is derived from:

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

Code

python3 复制代码
class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        m, n = len(matrix), len(matrix[0])
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        
        ans = 0
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if matrix[i-1][j-1] == '1':
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
                    if ans < dp[i][j]:
                        ans = dp[i][j]
        
        return ans * ans
相关推荐
春日见2 小时前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
图图的点云库3 小时前
高斯滤波实现算法
c++·算法·最小二乘法
rainbow7242443 小时前
AI人才简历评估选型:技术面试、代码评审与项目复盘的综合运用方案
人工智能·面试·职场和发展
一叶落4384 小时前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
努力学算法的蒟蒻4 小时前
day115(3.17)——leetcode面试经典150
面试·职场和发展
老鱼说AI4 小时前
CUDA架构与高性能程序设计:异构数据并行计算
开发语言·c++·人工智能·算法·架构·cuda
罗湖老棍子5 小时前
【例 1】数列操作(信息学奥赛一本通- P1535)
数据结构·算法·树状数组·单点修改 区间查询
big_rabbit05025 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode
张李浩6 小时前
Leetcode 15三题之和
算法·leetcode·职场和发展
2301_793804697 小时前
C++中的适配器模式变体
开发语言·c++·算法