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:

dpij = min(dpi-1j, dpij-1, dpi-1j-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
相关推荐
醇氧1 小时前
CountDownLatch / CyclicBarrier / Semaphore 面试高频问答清单
前端·面试·职场和发展
爱刷碗的苏泓舒3 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
谙弆悕博士4 小时前
系统集成项目管理工程师教程(第3版)笔记——第17章:法律法规和标准规范
笔记·职场和发展·学习方法·业界资讯·软考·法律·法规
烬羽6 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米6 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
星空露珠6 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA8 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel8 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客8 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
风栖柳白杨9 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试