美文网首页
LeetCode No.13最大正方形

LeetCode No.13最大正方形

作者: MRYDM | 来源:发表于2019-06-26 17:54 被阅读0次

1. LeetCode221题目链接链接

https://leetcode-cn.com/problems/maximal-square/submissions/

2.题目解析

该题目为在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。遍历矩阵所有数据,记录1的位置能组成的矩形,记录边长,循环找到最大的边长,然后返回面积。

public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        if(m < 1) return 0;
        int n = matrix[0].length;
        int max = 0;
        int[][] dp = new int[m+1][n+1];

        for(int i = 1; i <= m; ++i) {
            for(int j = 1; j <= n; ++j) {
                if(matrix[i-1][j-1] == '1') {
                    dp[i][j] = 1 + Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1]));
                    max = Math.max(max, dp[i][j]);
                }
            }
        }

        return max*max;
    }

3. 提交结果

提交结果

相关文章

网友评论

      本文标题:LeetCode No.13最大正方形

      本文链接:https://www.haomeiwen.com/subject/aakhcctx.html