力扣(LeetCode)221

栏目: 编程工具 · 发布时间: 6年前

内容简介:题目地址:题目描述:

题目地址:

https://leetcode-cn.com/probl...

题目描述:

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入:

1 0 1 0 0

1 0 1 1 1

1 1 1 1 1

1 0 0 1 0

输出: 4

解答:

这一题使用动态规划算法。dpi表示以点(i,j)为右下角点的最大正方形的边长,那么就有若matrixi = '0',dpi = 0,否则dpi = 1+min(dpi-1,min(dpi-1,dpi))

然后查找dpi的最大值max,返回max*max

java ac代码:

class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix.length == 0)return 0;
        
        int[][]dp = new int[matrix.length][matrix[0].length];
        for(int i = 0;i < matrix.length;i++)
            dp[i][0] = matrix[i][0]-'0';
        for(int j = 0;j < matrix[0].length;j++)
            dp[0][j] = matrix[0][j]-'0';
        
        for(int i = 1;i < matrix.length;i++)
            for(int j = 1;j < matrix[0].length;j++)
                if(matrix[i][j] != '0')
                dp[i][j] = 1+Math.min(Math.min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]);
        
        int max = 0;
        for(int i = 0;i < matrix.length;i++)
            for(int j = 0;j < matrix[0].length;j++)
                max = Math.max(dp[i][j],max);
        return max*max;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Definitive Guide to Django

The Definitive Guide to Django

Adrian Holovaty、Jacob Kaplan-Moss / Apress / 2007-12-06 / CAD 45.14

Django, the Python-based equivalent to the Ruby on Rails web development framework, is presently one of the hottest topics in web development today. In The Definitive Guide to Django: Web Development ......一起来看看 《The Definitive Guide to Django》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码