Middle-题目103:221. Maximal Square

题目原文:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
题目大意:
给出一个0-1矩阵,求其中最大的由1组成的正方形,返回其面积。
题目分析:
还是Dp问题,设dp[i][j]为右下角为(i,j)的正方形的边长,则有如下转移方程:
dp[i][j]=min(dp[i1][j],dp[i1][j1],dp[i][j1])+1
初始化第一行(列)的dp[0][i]和dp[j][0]为矩阵的原值。
这个转移方程用文字比较难以描述,在纸上画一下三种情况就很好理解了。
源码:(language:java)

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

成绩:
14ms,beats 58.15%,众数17ms,11.81%

阅读更多
版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs https://blog.csdn.net/cmershen/article/details/51548560
个人分类: Leetcode
上一篇Middle-题目102:150. Evaluate Reverse Polish Notation
下一篇Middle-题目104:43. Multiply Strings
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭