LintCode : Maximal Square

# LintCode : 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.

动态规划:

动态方程 dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;

原矩阵:

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

dp矩阵:

0 0 0 0 0 0
0 1 0 1 0 0
0 1 0 1 1 1
0 1 1 1 2 1
0 1 0 0 1 0

遍历dp矩阵,找到最大值maxNum,题目要求矩阵面积,则返回maxNum平方即可。


public class Solution {
    /** * @param matrix: a matrix of 0 and 1 * @return: an integer */
    public int maxSquare(int[][] matrix) {
        // write your code here
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m+1][n+1];
        for(int i=0; i<=m; i++){
            for(int j=0; j<=n; j++){
                if(i==0 || j==0){
                    dp[i][j] = 0;
                }
                else if(matrix[i-1][j-1] == 1){
                    dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1;
                }
                else{
                    dp[i][j] = 0;
                }
            }
        }
        int maxNum = 0;
        for(int i=0; i<=m; i++){
            for(int j=0; j<=n; j++){
                if(dp[i][j] > maxNum){
                    maxNum = dp[i][j];
                }
            }
        }
        return maxNum * maxNum;
    }
    public int min(int a, int b){
        return a < b ? a : b ;
    }
}

你可能感兴趣的:(LintCode : Maximal Square)