221. Maximal Square
发布日期:2021-05-04 11:02:44 浏览次数:27 分类:精选文章

本文共 1318 字,大约阅读时间需要 4 分钟。

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

动态规划

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

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

 

上一篇:222. Count Complete Tree Nodes
下一篇:LeetCode - 215. Kth Largest Element in an Array

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月14日 07时51分53秒