Leetcode刷题java之221. 最大正方形

执行结果:

通过

显示详情

执行用时 :6 ms, 在所有 Java 提交中击败了89.02% 的用户

内存消耗 :43.1 MB, 在所有 Java 提交中击败了30.81%的用户

题目:

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

示例:

输入: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

输出: 4

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

思路:

此题属于动态规划的题,就是首先判断当前节点是否是1,如果是,那么就取Math的最小值,在左,上,左上之间,再加上1。至于原因,读者可以利用例子体会一下。

代码:(这是我自己的代码,虽然思路清晰,但是代码写得还不够简洁,继续努力)

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

代码:(别人的代码,还真是挺简洁的)

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

作者:LeetCode
链接:https://leetcode-cn.com/problems/maximal-square/solution/zui-da-zheng-fang-xing-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
发布了481 篇原创文章 · 获赞 502 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/104231528