221. Maximal Square

Medium:
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.

这道题是看了讲解写的,其中有个地方以后一定要注意,就是char类型来进行比较的时候,不能直接跟int划等号。我一开始判断句写成了:

if (matrix[i][j] == 1)

这是错误的,正确的写法应该是:

if (matrix[i][j] == '1')

同理,一开始初始化第零行或者零列的元素时,不能写成:

f[0][j] = matrix[0][j];

正确的写法是:

f[0][j] = matrix[0][j] - '0';

总而言之,不能把char当int用,不管是a,b,c还是0,1,2,要得到int就得ch - 'a' 或者 4 - ‘0’这样通过求出char和'a'或者char和‘0’的差值来计算。当然了,也可以用自带的API来写,比如:

f[i][0] = Character.getNumericValue(matrix[i][0]);

关于动态规划,这道题

class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return 0;
        }
        int n = matrix.length;
        int m = matrix[0].length;
        //state:f[i][j] represents the maximal square whose lower-right corner is matrix[i][j]
        int[][] f = new int[n][m];
        //instantialize
        int maxLen = 0;
        for (int j = 0; j < m; j++){
            f[0][j] = matrix[0][j] - '0';
            maxLen = Math.max(maxLen, f[0][j]);
        }
        for (int i = 0; i < n; i++){
            f[i][0] = matrix[i][0] - '0';
            maxLen = Math.max(maxLen, f[i][0]);
        }
        //function
        for (int i = 1; i < n; i++){
            for (int j = 1; j < m; j++){
                if (matrix[i][j] == '1'){
                    f[i][j] = Math.min(Math.min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1;
                } else if (matrix[i][j] == '0'){
                    f[i][j] = 0;
                }
                maxLen = Math.max(maxLen, f[i][j]);
            }
            
        }
        return maxLen * maxLen;
    }
}

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