LeetCode221 最大正方形

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example:

Input:

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

Output: 4

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

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/86063195