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
相关推荐
mmmmath_36 小时前
LeetCode.199.二叉树的右视图
数据结构·leetcode
专注仿真6 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸6 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫6 小时前
2028编程圈很火的10个Skills
算法·面试·github
Nil20811 小时前
leetcode 198打家劫舍
算法·leetcode·职场和发展
Shaoshing11 小时前
前缀和与差分
java·数据结构·算法·前缀和·差分
mmmmath_311 小时前
LeetCode.429.N叉树的层序遍历
数据结构·leetcode
loulanyue_12 小时前
构建房产认知决策智能:Harness底座与AI自进化的技术实践——读贝壳首席算法科学家尹俊希2026云栖专场演讲
人工智能·算法
碧海银沙音频科技研究院12 小时前
基于炬芯ATS录音卡BLE控制协议
人工智能·嵌入式硬件·算法·语音识别
suhan13 小时前
【数据结构】三、栈和队列:6.链队列、双端队列、队列的应用(树的层次遍历、广度优先BFS、先来先服务FCFS)
数据结构·后端·算法