leetcode Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

dp,递归关系式:dp[x][y]=min(dp[x-1][y],dp[x][y-1],dp[x-1][y-1])+1,dp[x][y]代表以x,y为右下顶点的正方形的最长边长,代码:

public int maximalSquare(char[][] matrix) {
      int length=0;
    int[][] res=new int[matrix.length+1][matrix[0].length+1];
    for(int i=0;i<matrix.length;i++){
        for(int j=0;j<matrix[0].length;j++){
            if(matrix[i][j]=='1'){
                res[i+1][j+1]=Math.min(Math.min(res[i][j+1],res[i+1][j]),res[i][j])+1;
                if(res[i+1][j+1]>length) length=res[i+1][j+1];
            }
        }
    }
    return length*length;
}

阅读更多
文章标签: leetcode 算法
个人分类: leetcode
上一篇leetcode Reconsrtuct Itinerary
下一篇leetcode Simplify Path
想对作者说点什么? 我来说一句

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

关闭
关闭